LeetCode.M1282.用户分组

LeetCode.M1282

题目:

在这里插入图片描述

题目大意:

​ 如图所示。

数据范围:

如图所示

思路:

​ 简单模拟,使用HashMap将每个人归类,然后对每一类根据所在组的大小,拆分成小类。

代码:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class Solution {
    public List<List<Integer>> groupThePeople(int[] groupSizes) {

        List<List<Integer>> lists = new ArrayList<List<Integer>>();
        Map<Integer, List<Integer>> allgroup = new HashMap<>();
        for (int i = 0; i < groupSizes.length; i ++ ){
            List<Integer> a = allgroup.getOrDefault(groupSizes[i], new ArrayList<>());
            a.add(i);
            allgroup.put(groupSizes[i], a);
        }
        /*
        for (int i = 0; i < groupSizes.length; i++) {
            int size = groupSizes[i];
            allgroup.putIfAbsent(size, new ArrayList<Integer>());
            allgroup.get(size).add(i);
        }
         */


        for (Map.Entry<Integer, List<Integer>> gro : allgroup.entrySet()){
            int groId = gro.getKey();
            List<Integer> peoId = gro.getValue();
            int len = 0;
            while (len < peoId.size()){
                List<Integer> smallgro = new ArrayList<>();
                int cnt = 0;
                while (cnt < groId){
                    smallgro.add(peoId.get(len));
                    len ++ ;
                    cnt ++ ;
                }
                lists.add(smallgro);
            }
        }
        return lists;
    }
}

public class Main {
    public static void main(String[] args) {
        int[] groupSizes = new int[]{3,3,3,3,3,1,3};
        Solution solution = new Solution();
        System.out.println(solution.groupThePeople(groupSizes));
    }
}

时空复杂度分析等:

  • 时间复杂度 : O(n)

  • 空间复杂度 : O(n)

题目链接:

1282. 用户分组 - 力扣(LeetCode)

附:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值