We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 8c86a4c commit 0d8c4b8Copy full SHA for 0d8c4b8
top-k-frequent-elements/dylan-jung.cpp
@@ -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