---
# System prepended metadata

title: 1282. Group the People Given the Group Size They Belong To
tags: [C++, LeetCode-Medium]

---

# 1282. Group the People Given the Group Size They Belong To
Difficulty: Medium

## Solution

```cpp=
/**
*** Author: R-CO
*** E-mail: daniel1820kobe@gmail.com
*** Date: 2020-10-27
**/
#include <cstdlib> // EXIT_SUCCESS
#include <unordered_map>
using std::unordered_map;
#include <vector>
using std::vector;

using GroupSizeMap = unordered_map<int, vector<vector<int>>>;
using GroupSizeMapPair = std::pair<int, vector<vector<int>>>;

class Solution {
 public:
  vector<vector<int>> groupThePeople(vector<int>& groupSizes) {
    GroupSizeMap group_size_map;

    int people_id = 0;
    for (const auto group_size : groupSizes) {
      static auto assignGroup = [&group_size_map, &people_id, &group_size] (GroupSizeMap::iterator &itor) {
        auto &group_vec = itor->second.back();
        if (group_vec.size() < group_size) {
          group_vec.emplace_back(people_id);
        } else {
          itor->second.emplace_back(vector<int>{people_id});
        }
      };

      auto group_map_itor = group_size_map.find(group_size);
      if (group_map_itor != group_size_map.end()) {
        assignGroup(group_map_itor);
      } else {
        group_size_map.insert(
            GroupSizeMapPair(group_size, vector<vector<int>>{{}}));
        group_map_itor = group_size_map.find(group_size);
        assignGroup(group_map_itor);
      }

      ++people_id;
    }

    vector<vector<int>> output;
    for (auto group_map_itor : group_size_map) {
      auto &group_vecs = group_map_itor.second;
      for (auto &group : group_vecs) {
        output.emplace_back(std::move(group));
      }
    }

    return output;
  }
};

int main(int argc, char *argv[]) { return EXIT_SUCCESS; }

```

## Result

Success
Details 
Runtime: 16 ms, faster than 95.90% of C++ online submissions for Group the People Given the Group Size They Belong To.
Memory Usage: 15 MB, less than 12.02% of C++ online submissions for Group the People Given the Group Size They Belong To.


###### tags: `LeetCode-Medium` `C++`
