1282. 用户分组

1282. 用户分组
有 n 个人被分成数量未知的组。每个人都被标记为一个从 0 到 n - 1 的唯一ID 。

给定一个整数数组 groupSizes ,其中 groupSizes[i] 是第 i 个人所在的组的大小。例如,如果 groupSizes[1] = 3 ,则第 1 个人必须位于大小为 3 的组中。

返回一个组列表,使每个人 i 都在一个大小为 groupSizes[i] 的组中。

每个人应该 恰好只 出现在 一个组 中,并且每个人必须在一个组中。如果有多个答案,返回其中 任何 一个。可以 保证 给定输入 至少有一个 有效的解。

 

示例 1:

输入:groupSizes = [3,3,3,3,3,1,3]
输出:[[5],[0,1,2],[3,4,6]]
解释:
第一组是 [5],大小为 1,groupSizes[5] = 1。
第二组是 [0,1,2],大小为 3,groupSizes[0] = groupSizes[1] = groupSizes[2] = 3。
第三组是 [3,4,6],大小为 3,groupSizes[3] = groupSizes[4] = groupSizes[6] = 3。 
其他可能的解决方案有 [[2,1,6],[5],[0,4,3]][[5],[0,6,2],[4,3,1]]。
示例 2:

输入:groupSizes = [2,1,3,3,3,2]
输出:[[1],[0,5],[2,3,4]]
 

提示:

groupSizes.length == n
1 <= n <= 500
1 <= groupSizes[i] <= n

用List做标记,需要提前分配内存

class Solution {
    public List<List<Integer>> groupThePeople(int[] groupSizes) {
    	int n=groupSizes.length;
        List<List<Integer> > tmp=new ArrayList();
        for(int i=0;i<1000;++i)
        {
        	tmp.add(null);
        }
        List<List<Integer>> ans=new ArrayList();
        
        for(int i=0;i<n;++i)
        {
            int t=groupSizes[i];
            if(tmp.get(t)==null)tmp.set(t, new ArrayList());
            tmp.get(t).add(i);
            if(tmp.get(t).size()==t)
            {
                ans.add(tmp.get(t));
                tmp.set(t,null);
            }
        }
        return ans;
    }
}
哈希表

class Solution {
    public List<List<Integer>> groupThePeople(int[] groupSizes) {
    	int n=groupSizes.length;
        HashMap<Integer,List<Integer>> tmp=new HashMap<Integer,List<Integer>>();
        List<List<Integer>> ans=new LinkedList<List<Integer>>();
        
        for(int i=0;i<n;++i)
        {
            int t=groupSizes[i];
            if(!tmp.containsKey(t))tmp.put(t, new ArrayList<Integer>());
            tmp.get(t).add(i);
            if(tmp.get(t).size()==t)
            {
                ans.add(tmp.get(t));
                tmp.remove(t);
            }
        }
        return ans;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wow_awsl_qwq

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值