LeetCode

    科技2025-05-19  7

    //有 n 位用户参加活动,他们的 ID 从 0 到 n - 1,每位用户都 恰好 属于某一用户组。 //给你一个长度为 n 的数组 groupSizes,其中包含每位用户所处的用户组的大小, //请你返回用户分组情况(存在的用户组以及每个组中用户的 ID)。 //你可以任何顺序返回解决方案,ID 的顺序也不受限制。此外,题目给出的数据保证至少存在一种解决方案。 //示例 1: //输入:groupSizes = [3,3,3,3,3,1,3] //输出:[[5],[0,1,2],[3,4,6]] //解释: //其他可能的解决方案有 [[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 public class Solution1282 { public static void main(String[] args) { int[] i= {3,3,3,3,3,1,3,4,4,4,4}; List<List<Integer>> list=groupThePeople(i); for (List<Integer> list2 : list) { System.out.println(list2); } } public static List<List<Integer>> groupThePeople(int[] groupSizes) { List<List<Integer>> res=new ArrayList<>();//结果集 Map<Integer,List<Integer>> map=new HashMap<>();//代表着用户和对应id的键值关系 for (int i = 0; i < groupSizes.length; i++) { if(!map.containsKey(groupSizes[i])) map.put(groupSizes[i], new ArrayList<>());//如果不存在这个的键值关系,就new一个新的关系,但是这个是一个没有名字的关系 List<Integer> temp=map.get(groupSizes[i]);//返回这个指定关系对应的value temp.add(i);//添加下标 //如果长度刚好是对应的分组的长度,就可以添加到res if(temp.size()==groupSizes[i]) { res.add(new ArrayList<>(temp)); temp.clear();//清除里面的全部内容 } } return res; }
    Processed: 0.010, SQL: 8