Sunday, December 8, 2019

Leetcode 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/description/


Notes:

The first step we need to category the elements based on the group size of the group they belong to.

Then the next step we just group the elements based on their group sizes.

Greedy can solve it, since there is no other requirements.

See the code below:

class Solution {
public:
    vector<vector<int>> groupThePeople(vector<int>& groupSizes) {
        vector<vector<int>> res;
        unordered_map<int, vector<int>> mp;
        for(int i=0; i<groupSizes.size(); ++i) mp[groupSizes[i]].push_back(i);
        for(auto &a : mp) {
            int i= 0, key = a.first;
            auto vs = a.second;
            while(i<vs.size()) {
                vector<int> t;
                while(t.size() < key) {
                    t.push_back(vs[i]);
                    ++i;
                }
                res.push_back(t);
            }
        }
        return res;
    }
};

No comments:

Post a Comment