Skip to content

Commit 0d8c4b8

Browse files
committed
top-k-freq-elems solutions
1 parent 8c86a4c commit 0d8c4b8

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
public:
3+
vector<int> topKFrequent(vector<int>& nums, int k) {
4+
unordered_map<int, int> m;
5+
map<int, vector<int>> freq;
6+
for(auto i: nums) m[i] += 1;
7+
for(auto item: m) {
8+
auto [k, v] = item;
9+
freq[v].push_back(k);
10+
}
11+
12+
vector<int> ans;
13+
ans.reserve(k);
14+
auto it = freq.rbegin();
15+
while(k > 0) {
16+
auto kth = it->second;
17+
ans.insert(ans.end(), kth.begin(), kth.end());
18+
k-=kth.size();
19+
it++;
20+
}
21+
return ans;
22+
}
23+
};

0 commit comments

Comments
 (0)