---
# System prepended metadata

title: 1282. Group the People Given the Group Size They Belong To
tags: [Leetcode, Medium]

---

# 1282. Group the People Given the Group Size They Belong To
###### tags: `Leetcode` `Medium`
Link: https://leetcode.com/problems/group-the-people-given-the-group-size-they-belong-to/description/
## 思路
Keep track of people in each group based on the group size. Greedily assign people to the corresponding group.

As soon as the group is filled, add it to the result and reset the list of its members.
## Code
```java=
class Solution {
    public List<List<Integer>> groupThePeople(int[] groupSizes) {
        List<List<Integer>> ans = new ArrayList<>();
        Map<Integer, List<Integer>> map = new HashMap<>();
        for(int i=0; i<groupSizes.length; i++){
            if(!map.containsKey(groupSizes[i])){
                map.put(groupSizes[i], new ArrayList<>());
            }
            map.get(groupSizes[i]).add(i);
            if(map.get(groupSizes[i]).size()==groupSizes[i]){
                ans.add(new ArrayList<>(map.get(groupSizes[i])));
                map.remove(groupSizes[i]);
            }
        }
        return ans;
    }
}
```