LeetCode——1282. User Group

Title description:

There are n users participating in the activity, their IDs range from 0 to n-1, and each user happens to belong to a certain user group. Give you an array of length n groupSizes, which contains the size of the user group that each user belongs to. Please return the user grouping situation (the existing user groups and the ID of the user in each group).
You can return solutions in any order, and the order of IDs is not limited. In addition, the data given by the question guarantees that there is at least one solution.

prompt

  • groupSizes.length == n
  • 1 <= n <= 500
  • 1 <= groupSizes[i] <= n

Example 1:
Input: groupSizes = [3,3,3,3,3,1,3]
Output: [[5],[0,1,2],[3,4,6]]
Explanation:
Other possible The solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].

Example 2:
Input: groupSizes = [2,1,3,3,3,2]
Output: [[1],[0,5],[2,3,4]]

code show as below:

class Solution {
    
    
    public List<List<Integer>> groupThePeople(int[] groupSizes) {
    
    
        List<List<Integer>> list = new ArrayList<>();
        HashSet<Integer> set = new HashSet<>();
        int n = groupSizes.length;
        for (int i = 0; i < n; i++) {
    
    
            List<Integer> array = new ArrayList<>();
            int num = groupSizes[i];
            if (set.contains(num)) {
    
    
                continue;
            }
            for (int j = i; j < n; j++) {
    
    
                if (groupSizes[j] == num) {
    
    
                    array.add(j);
                    if (array.size() == num) {
    
    
                        list.add(new ArrayList<>(array));
                        array.clear();
                    }
                }
            }
            set.add(groupSizes[i]);
        }
        return list;
    }
}

Results of the:
Insert picture description here

Guess you like

Origin blog.csdn.net/FYPPPP/article/details/114927942