【貪心】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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章