• 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

  • 相关阅读:
    手机怎么知道5G基站的存在?(小区搜索和SSB简介)
    Python中*args,**kwargs两个参数的作用?
    python之jupyter的安装
    国内安装python库速度慢的解决办法
    MOSFET:金属-氧化物半导体场效应晶体管
    C# 小知识点汇总
    ajax和form和七个中间件
    BBS功能分析
    MVC和MTV
    自关联和auth模块
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12065706.html
Copyright © 2020-2023  润新知