无尽算法之 用户分组

有 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

思路:

使用Hashmap
以groupSize为key, 以ArrayList(ArrayList())为value, 这里存放的Integer就是userId(也就是数组index)
插入策略:
先判断是否有key,无key则直接生成新的ArrayList(ArrayList()), 并且添加一个子ArrayList, 同时插入userId
有key再判断取出的ArrayList内部的最后一个ArrayList长度是否等于对应的groupSize, 如果相等, 则追加到新组, 否则追加到旧组.

题解:

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

    private static HashMap<Integer, ArrayList> resultMap = new HashMap<>();

    public static List<List<Integer>> groupThePeople(int[] groupSizes) {
        ArrayList<List<Integer>> results = new ArrayList<>();
        for (int i=0;i<groupSizes.length;i++) {
            add(i,groupSizes[i]);
        }
        for (ArrayList i : resultMap.values()) {
            results.addAll(i);
        }
        return results;
    }

    static void  add(int id, int groupSize) {
        if (resultMap.get(groupSize) == null) {
            ArrayList<List<Integer>> groupList = new ArrayList<>();
            List<Integer> group=new ArrayList<>();
            group.add(id);
            groupList.add(group);
            resultMap.put(groupSize, groupList);
        } else {
            ArrayList<List<Integer>> a = resultMap.get(groupSize);
            if (a.get(a.size() - 1).size() == groupSize ) {
                List<Integer> group=new ArrayList<>();
                group.add(id);
                a.add(group);
            } else {
                a.get(a.size() - 1).add(id);
            }
        }
    }
}
发布了125 篇原创文章 · 获赞 236 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_33709508/article/details/103840182