Skip to content

Commit 463b6d6

Browse files
authored
Merge pull request neetcode-gh#64 from Pegasus02K/patch-3
Create 347-Top-K-Frequent-Elements.cpp
2 parents 9588483 + b583c6a commit 463b6d6

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution {
2+
public:
3+
vector<int> topKFrequent(vector<int>& nums, int k) {
4+
unordered_map<int, int> count;
5+
for (int n : nums) {
6+
++count[n];
7+
}
8+
9+
vector<vector<int>> freq(nums.size() + 1, vector<int>());
10+
for (auto e : count) {
11+
freq[e.second].push_back(e.first);
12+
}
13+
14+
vector<int> result;
15+
for (int i = freq.size()-1; i >= 0; --i) {
16+
for (int n : freq[i]) {
17+
result.push_back(n);
18+
if (result.size() == k)
19+
return result;
20+
}
21+
}
22+
return result;
23+
}
24+
};

0 commit comments

Comments
 (0)