温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

无尽算法之用户编组

发布时间:2020-08-11 09:32:49 来源:网络 阅读:161 作者:专注地一哥 栏目:编程语言

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

groupSizekey, 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<>();

    function(){ //点差 http://www.kaifx.cn/question/kaifx/1799.html

        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);

            }

        }

    }

}

 


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI