Skip to content

Commit bfef3ca

Browse files
authored
Update Top K Frequent Elements - Leetcode 347.cpp
1 parent d79ab13 commit bfef3ca

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

Top K Frequent Elements - Leetcode 347/Top K Frequent Elements - Leetcode 347.cpp

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,56 @@
1+
2+
#include <vector>
3+
#include <unordered_map>
4+
#include <queue>
5+
#include <algorithm>
6+
using namespace std;
7+
8+
class Solution {
9+
public:
10+
vector<int> topKFrequent(vector<int>& nums, int k) {
11+
unordered_map<int, int> countMap;
12+
for (int num : nums) {
13+
countMap[num]++;
14+
}
15+
16+
auto cmp = [](const pair<int, int>& a, const pair<int, int>& b) {
17+
return a.second > b.second;
18+
};
19+
20+
priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> minHeap(cmp);
21+
22+
for (auto& entry : countMap) {
23+
if (minHeap.size() < k) {
24+
minHeap.push(entry);
25+
} else {
26+
minHeap.push(entry);
27+
minHeap.pop();
28+
}
29+
}
30+
31+
vector<int> topK;
32+
while (!minHeap.empty()) {
33+
topK.push_back(minHeap.top().first);
34+
minHeap.pop();
35+
}
36+
37+
reverse(topK.begin(), topK.end());
38+
return topK;
39+
}
40+
};
41+
42+
43+
44+
45+
46+
47+
48+
49+
50+
51+
52+
53+
154
#include <vector>
255
#include <unordered_map>
356
#include <unordered_set>

0 commit comments

Comments
 (0)