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.python
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. c++
Example 1:數組
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]].
Example 2:app
Input: groupSizes = [2,1,3,3,3,2] Output: [[1],[0,5],[2,3,4]]
Constraints:spa
groupSizes.length == n
1 <= n <= 500
1 <= groupSizes[i] <= n
題目大意:有n我的,編號0到n-1,每一個人只屬於一個組,給定一個長度爲n的數組gs,gs[i]表示編號爲i的人所在組的人數,返回任意一個可能的分組。題目保證存在至少一種分組。code
思路:每一個人能夠獨立成組,也能夠全部人都在一個組,因此可能的組的人數爲1-n,咱們把 組的人數相同 的人的編號放在同一個組group,最後根據組的人數進行分割分別成組(或者每當這個組達到上限,就把組內全部人放在最終的組,把當前組清空)blog
c++:it
1 class Solution { 2 public: 3 vector<vector<int>> groupThePeople(vector<int>& gs) { 4 // vector<vector<int>> res; 5 // //unordered_map<int, vector<int>> G; 6 // vector<vector<int>> G(gs.size() + 1); 7 // for (int i = 0; i < gs.size(); ++i) { 8 // G[gs[i]].push_back(i); 9 // if (G[gs[i]].size() == gs[i]) { 10 // res.push_back(G[gs[i]]); 11 // G[gs[i]].clear(); 12 // } 13 // } 14 // return res; 15 vector<vector<int>> res; 16 unordered_map<int,vector<int>> mp; 17 for (int i = 0; i < gs.size(); ++i) { 18 mp[gs[i]].push_back(i); 19 } 20 for (auto x : mp) { 21 int i = x.first; //i表示組的人數 22 vector<int> v = x.second; //能夠放在同一個組的全部人的編號 23 vector<int> t(i); //每i我的放一個組 24 for (int j = 0; j < v.size(); ++j) { 25 t[j % i] = v[j]; 26 if ((j + 1) % i == 0) { 27 res.push_back(t); 28 } 29 } 30 } 31 return res; 32 } 33 };
python3:io
1 class Solution: 2 def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]: 3 count = collections.defaultdict(list) 4 for i, size in enumerate(groupSizes): 5 count[size].append(i) 6 return [v[i:i+size] for size, v in count.items() for i in range(0, len(v), size)]