-
Notifications
You must be signed in to change notification settings - Fork 110
/
692-top-k-frequent-words.cpp
50 lines (43 loc) · 1.39 KB
/
692-top-k-frequent-words.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
41
42
43
44
45
46
47
48
49
50
#include <queue>
#include <map>
class Solution {
public:
struct KeyWithFreq {
string key;
int times;
KeyWithFreq(string a, int b) : key(a), times(b) {};
};
vector<string> topKFrequent(vector<string>& words, int k) {
map<string, int> counts;
for (string word : words) {
auto it = counts.find(word);
if (it != counts.end()) {
it->second++;
} else {
counts[word] = 1;
}
}
priority_queue<KeyWithFreq, vector<KeyWithFreq>, function<bool(KeyWithFreq, KeyWithFreq)>>
min_heap([](const KeyWithFreq& a, const KeyWithFreq& b) {
if (a.times < b.times) {
return true;
} else if (a.times == b.times) {
if (a.key > b.key) {
return true;
}
}
return false;
});
auto it = counts.begin();
while (it != counts.end()) {
min_heap.emplace(KeyWithFreq(it->first, it->second));
it++;
}
vector<string> result;
for (int i = 0; i < k; i++) {
result.push_back(min_heap.top().key);
min_heap.pop();
}
return result;
}
};