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

https://leetcode.com/problems/group-the-people-given-the-group-size-they-belong-to/

数组元素数字代表该元素所在组的大小,让返回任意一种满足条件的分组方式,假设至少存在一种合理的分组。把每个元素放到它size对应的组,满了时就建一个新组。

class Solution {
public:
    vector<vector<int>> groupThePeople(vector<int>& groupSizes) {
        unordered_map<int, vector<int>> groups;
        vector<vector<int>> res;
        for (int i = 0; i < groupSizes.size(); ++i) {
            const auto s = groupSizes[i];
            groups[s].push_back(i);
            if (groups[s].size() == s) {
                res.push_back(groups[s]);
                groups[s].clear();
            }
        }
        return res;
    }
};

Last updated