leetcode第1282题
题目
有一说一这题的中文题目太难懂了,看英文比较好懂
There are n people that are split into some
unknown number of groups. Each person is labeled with a unique ID from
0 to n - 1.You are given an integer array groupSizes, where groupSizes[i] is the
size of the group that person i is in. For example, if groupSizes[1] =
3, then person 1 must be in a group of size 3.Return a list of groups such that each person i is in a group of size
groupSizes[i].Each person should appear in exactly one group, and every person must
be in a group. If there are multiple answers, return any of them. It
is guaranteed that there will be at least one valid solution for the
given input.
Input: groupSizes = [3,3,3,3,3,1,3]
Output: [[5],[0,1,2],[3,4,6]]
解释
简单来说翻译成中文就是
一个数组[3,3,3,3,3,1,3],groupSizes[5] = 1表示第五个下标对应的人在1人组,groupSizes[0] = 3表示第0个下标对应的人在3人组,所以在三人组的就有[0,1,2,3,4,6],第5个下标在1人组,所以就把在3人组的人每三个人分一个组,所以就有两个组[0,1,2]和[3,4,6]然后还有[5]在一人组,所以分组的情况就是[[5],[0,1,2],[3,4,6]]
思路
- 先遍历一遍数组,看看把在同一规模的组的人放在一起,用哈希表来统计,这样就把同一个规模的人放在一个数组里,用对应的人数规模来当索引。
- 然后再把相同人数规模的数组按人数规模来划分,比如三人组有6个人,那就三个三个一组,分成两组,并把分成的组记录下来加入到res数组里
class Solution {
public:
vector<vector<int>> groupThePeople(vector<int>& groupSizes) {
map<int,vector<int>>mp;
vector<vector<int>>res;
//记录每一种规模的用户组对应哪些坐标,比如[3,3,3,3,3,1,3]中,属于3人组的人有0,1,2,3,4,6号坐标
for(int i=0;i<groupSizes.size();i++)
{
mp[groupSizes[i]].push_back(i);
}
//把每种规模的组进行分组,比如属于三人组的有0,1,2,3,4,6号坐标,那就从mp[3]里不断取三个人分为一个组,就可以分成[0,1,2]和[3,4,6]这两组
//遍历每种规模的组
for(auto&it:mp)
{
vector<int>temp;
//遍历每种规模x的组对应的人,依次取x个人作为一组
for(int i=0;i<it.second.size();i++)
{
temp.push_back(it.second[i]);
//如果达到了x个人,就把这一组加入到结果数组里面,然后把当前的存储组的结果清空
if(temp.size()==it.first)
{
res.push_back(temp);
temp.clear();
}
}
}
return res;
}
};