有 n 位用戶參加活動,他們的 ID 從 0 到 n - 1,每位用戶都 恰好 屬于某一用戶組。給你一個長度為 n 的數組 groupSizes,其中包含每位用戶所處的用戶組的大小,請你返回用戶分組情況(存在的用戶組以及每個組中用戶的 ID)。
你可以任何順序返回解決方案,ID 的順序也不受限制。此外,題目給出的數據保證至少存在一種解決方案。
示例 1:
輸入:groupSizes = [3,3,3,3,3,1,3]
輸出:[[5],[0,1,2],[3,4,6]]
解釋:
其他可能的解決方案有 [[2,1,6],[5],[0,4,3]] 和 [[5],[0,6,2],[4,3,1]]。
代碼
class Solution {public List<List<Integer>> groupThePeople(int[] groupSizes) {int n=groupSizes.length;List<List<Integer>> res=new ArrayList<>();Map<Integer,List<Integer>> map=new HashMap<>();for(int i=0;i<n;i++){if(!map.containsKey(groupSizes[i]))map.put(groupSizes[i],new ArrayList<>());map.get(groupSizes[i]).add(i);//加入該組if(map.get(groupSizes[i]).size()==groupSizes[i])//分組的人數夠了{res.add(new ArrayList<>(map.get(groupSizes[i])));map.get(groupSizes[i]).clear();//清空分組}}return res;}
}