溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

無盡算法中的用戶分組實現(xiàn)

發(fā)布時間:2020-06-10 15:51:05 來源:億速云 閱讀:321 作者:元一 欄目:編程語言

算法(Algorithm)是指解題方案的準確而完整的描述,是一系列解決問題的清晰指令,算法代表著用系統(tǒng)的方法描述解決問題的策略機制。

n 位用戶參加活動,他們的 ID 0 n - 1,每位用戶都 恰好 屬于某一用戶組。給你一個長度為 n 的數(shù)組 groupSizes,其中包含每位用戶所處的用戶組的大小,請你返回用戶分組情況(存在的用戶組以及每個組中用戶的 ID)。

 

你可以任何順序返回解決方案,ID 的順序也不受限制。此外,題目給出的數(shù)據(jù)保證至少存在一種解決方案。

 

示例 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(也就是數(shù)組index)

插入策略:

先判斷是否有key,無key則直接生成新的ArrayList(ArrayList()), 并且添加一個子ArrayList, 同時插入userId

key再判斷取出的ArrayList內(nèi)部的最后一個ArrayList長度是否等于對應(yīng)的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問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI