C++代码
class Solution {
public:
vector<vector<int>> groupThePeople(vector<int>& groupSizes) {
vector<vector<int>> res;
unordered_map<int, vector<int>> has;
for(int i = 0; i < groupSizes.size(); i++){
int val = groupSizes[i];
has[val].push_back(i);
if(has[val].size() == val){
res.push_back(has[val]);
has[val].clear();
}
}
return res;
}
};
python代码
class Solution:
def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
hash = {}
res = []
for i in range(len(groupSizes)):
val = groupSizes[i]
if val not in hash: hash[val] = []
hash[val].append(i)
if len(hash[val]) == val:
res.append(hash[val])
hash[val] = []
return res