leetcode1282-用户分组

用户分组

  • 哈希分类

给每一个组别容量分配一个List,存入哈希表中。遍历数组,将当前下标加入对应数量的List中。
如果List数量满了,那么将其从map中删除并存入返回值。

class Solution {
    public List<List<Integer>> groupThePeople(int[] groupSizes) {
        List<List<Integer>> list = new ArrayList<>();
        Map<Integer, List<Integer>> map = new HashMap<>();
        for(int i = 0; i < groupSizes.length; i++){
            if(!map.containsKey(groupSizes[i])) map.put(groupSizes[i], new ArrayList<Integer>());
            List<Integer> l = map.get(groupSizes[i]);
            l.add(i);
            if(l.size() == groupSizes[i]){
                list.add(l);
                map.remove(groupSizes[i]);
            }
        }
        return list;
    }
}
posted @ 2022-08-15 23:53  xzh-yyds  阅读(31)  评论(0)    收藏  举报