用户分组问题

目录

LeetCode链接:https://leetcode.cn/problems/group-the-people-given-the-group-size-they-belong-to/

题目描述

解法


LeetCode链接:https://leetcode.cn/problems/group-the-people-given-the-group-size-they-belong-to/

题目描述

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

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

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

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

解法

class Solution {
    public List<List<Integer>> groupThePeople(int[] groupSizes) {
        Map<Integer,List<Integer>> hash = new HashMap<>();
        List<List<Integer>> res = new ArrayList<>();
        for(int i = 0; i < groupSizes.length; i++){
            int x = groupSizes[i];
            if(hash.get(x)==null) hash.put(x,new ArrayList<>());
            hash.get(x).add(i);
            if(hash.get(x).size()==x){
                res.add(hash.get(x));
                hash.put(x,null);
            }
        }
        return res;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值