【贪心】B041_LC_用户分组(map + 反向思维)

一、Problem

There are n people whose IDs go from 0 to n - 1 and each person belongs exactly to one group. Given the array groupSizes of length n telling the group size each person belongs to, return the groups there are and the people’s IDs each group includes.

You can return any solution in any order and the same applies for IDs. Also, it is guaranteed that there exists at least one solution.

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

Constraints:

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

二、Solution

方法一:map

这题稍微有点反向思维:不是真的遍历一下数组看有多少个组,然后对号入组那样,而是以组大小为 key,将对应组员添加到 key 对应的列表中,如果列表满足 gs[i] 个,那么某个组就分配完毕。

class Solution {
    public List<List<Integer>> groupThePeople(int[] gs) {
        List<List<Integer>> ans = new LinkedList<>();
        Map<Integer, List<Integer>> mp = new HashMap<>();

        for (int i = 0; i < gs.length; i++) {
            mp.computeIfAbsent(gs[i], v -> new LinkedList<>()).add(i);
            if (mp.get(gs[i]).size() == gs[i]) {
                ans.add(mp.get(gs[i]));
                mp.remove(gs[i]);
            }
        }
        return ans;
    }
}

复杂度分析

  • 时间复杂度:O(n)O(n)
  • 空间复杂度:O(n)O(n)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章