Endless algorithm of grouping users

There are n users to participate in activities, their ID from 0 to n - 1 , each user happens to belong to a particular group of users. You give a length of n array groupSizes , which contains the size of each user's user group, you return to user grouping (user group as well as the presence of users in each group ID ).

 

You can return any order solutions, ID sequence is not limited. Further, the subject data analysis to ensure the presence of at least one solution.

 

Example 1 :

Input: groupSizes = [. 3,. 3,. 3,. 3,. 3,. 1,. 3]

Output: [[5], [0, 1, 2], [3, 4, 6]]

 

There are other possible solutions

[ [ 2, 1, 6 ], [ 5 ], [ 0, 4, 3] ]

with

[ [ 5 ], [ 0, 6, 2 ] ,[ 4, 3, 1 ] ]

 

Example 2 :

Input: groupSizes = [2,. 1,. 3,. 3,. 3, 2]

Output: [[1], [0, 5], [2, 3, 4]]

 

prompt:

groupSizes.length == n

1 <= n <= 500

1 <= groupSizes[i] <= n

 

Ideas:

Use Hashmap

To groupSize as a key, to ArrayList (ArrayList ()) for the value, here stored Integer is userId ( that is, the array index)

Insertion strategies:

First determine whether there is key , no key directly generates new the ArrayList (the ArrayList ()) , and adding a sub ArrayList, while inserting userId

There are key then withdrawn determination ArrayList last inside ArrayList whether the length equal to the corresponding groupSize , if they are equal, then a new group is added, or additionally

answer:

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 () {// Spread 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);

            }

        }

    }

}

 


Guess you like

Origin blog.51cto.com/14511863/2464634