-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy path347-top-k-frequent-elements.cpp
40 lines (32 loc) · 1.08 KB
/
347-top-k-frequent-elements.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
class Solution {
public:
struct KeyWithFreq {
int key;
int times;
KeyWithFreq(int a, int b) : key(a), times(b) {};
};
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> counts;
for (int a : nums) {
auto it = counts.find(a);
if (it != counts.end()) {
it->second++;
} else {
counts[a] = 1;
}
}
priority_queue<KeyWithFreq, vector<KeyWithFreq>, function<bool(KeyWithFreq, KeyWithFreq)>>
min_heap([](const KeyWithFreq &a, const KeyWithFreq &b) { return a.times <= b.times; });
auto it = counts.begin();
while (it != counts.end()) {
min_heap.emplace(KeyWithFreq(it->first, it->second));
it++;
}
vector<int> result;
for (int i = 0; i < k; i++) {
result.push_back(min_heap.top().key);
min_heap.pop();
}
return result;
}
};