[LeetCode] Top K Frequent Words

692. Top K Frequent Words

Given a non-empty list of words, return the k most frequent elements.

Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
typedef pair<int, string> p;
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> m;
auto cmp = [](p const& a, p const& b) { return a.first == b.first ? a.second > b.second : a.first < b.first; };
priority_queue<p, vector<p>, decltype(cmp)> pq(cmp);
vector<string> res;
for(auto& w : words) {
m[w]++;
}

for(auto& e : m) {
pq.push({e.second, e.first});
}

while(k--) {
res.push_back(pq.top().second);
pq.pop();
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/07/PS/LeetCode/top-k-frequent-words/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.