-
Notifications
You must be signed in to change notification settings - Fork 521
/
Copy pathGroup The People Given By Group Size.cpp
65 lines (55 loc) · 1.99 KB
/
Group The People Given By Group Size.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//https://leetcode.com/problems/group-the-people-given-the-group-size-they-belong-to/
class Solution {
public:
// Naive Approach : Test Case passes
// Learning : intialise extra space in data structure (and loops) to avoid buffer-overflow ( Example in number 9 , 26)
/*vector<vector<int>> groupThePeople(vector<int>& gs) {
vector<vector<int> > ans ;
vector<int> tmp ;
vector< pair<int , vector<int> > > freq(gs.size() + 1, {0, {}} ) ;
for(int i = 0 ; i < gs.size() ; ++i){
++freq[gs[i]].first ;
freq[gs[i]].second.push_back(i);
}
//debug
for( auto s : freq){
cout << s.first << " " ;
for(auto x : s.second){
cout << x << "," ;
}
cout << endl ;
}
for(int i = 1 ; i < gs.size() + 1; ++i){
if(freq[i].first > 0){
int n = i , rem = freq[i].first/i;
while(rem > 0){
n = i ;
while(n>0){
tmp.push_back( freq[i].second.back());
freq[i].second.pop_back();
--n ;
}
/*for(auto s : tmp){
cout << "TMP " << s << endl ;
//}
ans.push_back(tmp) ;
tmp.clear();
--rem ;
}
}
}
return ans ;
}*/
// Another Solution found on Discussion Tab
vector<vector<int>> groupThePeople(vector<int>& gz) {
vector<vector<int>> res, groups(gz.size() + 1);
for (auto i = 0; i < gz.size(); ++i) {
groups[gz[i]].push_back(i);
if (groups[gz[i]].size() == gz[i]) {
res.push_back({});
swap(res.back(), groups[gz[i]]);
}
}
return res;
}
};