1282. Group the People Given the Group Size They Belong To

Posted wentiliangkaihua

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1282. Group the People Given the Group Size They Belong To相关的知识,希望对你有一定的参考价值。

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

以上是关于1282. Group the People Given the Group Size They Belong To的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 1282. 用户分组

算法1282. 用户分组(多语言实现)

算法1282. 用户分组(多语言实现)

LeetCode-第 166 场周赛

[LeetCode] 2418. Sort the People

Draft Export Control Law of the People’s Republic of China