Skip to content

Commit 6442928

Browse files
authored
Update Group the People Given the Group Size They Belong To.java
1 parent 42c41ac commit 6442928

File tree

1 file changed

+14
-16
lines changed

1 file changed

+14
-16
lines changed
Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,18 @@
11
class Solution {
2-
public List<List<Integer>> groupThePeople(int[] groupSizes) {
3-
Map<Integer, Queue<Integer>> groupSizeToId = new HashMap<>();
4-
for (int i = 0; i < groupSizes.length; i++) {
5-
groupSizeToId.computeIfAbsent(groupSizes[i], k -> new LinkedList<>()).add(i);
6-
}
7-
List<List<Integer>> result = new ArrayList<>();
8-
for (Integer groupSize : groupSizeToId.keySet()) {
9-
Queue<Integer> ids = groupSizeToId.get(groupSize);
10-
while (!ids.isEmpty()) {
11-
List<Integer> group = new ArrayList<>(groupSize);
12-
for (int i = 0; i< groupSize; i++) {
13-
group.add(ids.remove());
2+
public List<List<Integer>> groupThePeople(int[] groupSizes) {
3+
Map<Integer, List<Integer>> map = new HashMap<>();
4+
for (int i = 0; i < groupSizes.length; i++) {
5+
map.computeIfAbsent(groupSizes[i], k -> new ArrayList<>()).add(i);
6+
}
7+
List<List<Integer>> result = new ArrayList<>();
8+
for (Integer key : map.keySet()) {
9+
List<Integer> candidates = map.get(key);
10+
int idx = 0;
11+
while (idx < candidates.size()) {
12+
result.add(candidates.subList(idx, idx + key));
13+
idx += key;
14+
}
1415
}
15-
result.add(group);
16-
}
16+
return result;
1717
}
18-
return result;
19-
}
2018
}

0 commit comments

Comments
 (0)