leetcode 1282. Group the People Given the Group Size They Belong To

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. 

 

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:

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

 

Constraints:

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

题目大意:有n个人,编号0到n-1,每个人只属于一个组,给定一个长度为n的数组gs,gs[i]表示编号为i的人所在组的人数,返回任意一个可能的分组。题目保证存在至少一种分组。

 

思路:每个人可以独立成组,也可以所有人都在一个组,所以可能的组的人数为1-n,我们把 组的人数相同 的人的编号放在同一个组group,最后根据组的人数进行分割分别成组(或者每当这个组达到上限,就把组内所有人放在最终的组,把当前组清空)

c++:

 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:

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)]

 

posted @ 2019-12-09 14:07  琴影  阅读(625)  评论(0编辑  收藏  举报