There are n
people whose IDs go from 0
to n - 1
and each person belongs exactly to one group. Given the array groupSizes
of length n
telling the group size each person belongs to, return the groups there are and the people's IDs each group includes.
You can return any solution in any order and the same applies for IDs. Also, it is guaranteed that there exists at least one solution.
Example 1:
Input: groupSizes = [3,3,3,3,3,1,3] Output: [[5],[0,1,2],[3,4,6]] Explanation: Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].
Example 2:
Input: groupSizes = [2,1,3,3,3,2] Output: [[1],[0,5],[2,3,4]]
Constraints:
groupSizes.length == n
1 <= n <= 500
1 <= groupSizes[i] <= n
class Solution { public List<List<Integer>> groupThePeople(int[] groupSizes) { List<List<Integer>> res = new ArrayList(); Map<Integer, List<Integer>> map = new HashMap(); for(int i = 0; i < groupSizes.length; i++){ int cur = groupSizes[i]; if(!map.containsKey(cur)) map.put(cur, new ArrayList()); List<Integer> curr = map.get(cur); curr.add(i); if(curr.size() == cur){ res.add(curr); map.remove(cur); } } return res; } }
hint1:把所有element大小相同的index放到同一个bucket里(用hashmap和arraylist实现),
hint2:用greedy,遍历时每次取出当前bucket,如果长度够了就放到res里,然后map清空(删除)当前bucket