码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-12-19 09:47:12      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:nta   bucket   output   list()   contains   list   color   app   people   

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

标签:nta   bucket   output   list()   contains   list   color   app   people   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12065706.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!