-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathLeetCode_692_41.cpp
More file actions
36 lines (36 loc) · 986 Bytes
/
LeetCode_692_41.cpp
File metadata and controls
36 lines (36 loc) · 986 Bytes
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
/*
* @lc app=leetcode id=692 lang=cpp
*
* [692] Top K Frequent Words
*/
class Solution
{
public:
vector<string> topKFrequent(vector<string> &words, int k)
{
vector<string> res;
unordered_map<string, int> m;
auto comp = [](pair<int, string> &a, pair<int, string> &b) {
// first为出现次数,second为字母顺序排列
return a.first == b.first ? a.second < b.second : a.first > b.first;
};
priority_queue<pair<int, string>, vector<pair<int, string>>, decltype(comp)> pq(comp);
for (auto x : words)
{
m[x]++;
}
for (auto x : m)
{
pq.push({x.second, x.first});
if (pq.size() > k)
pq.pop();
}
while (!pq.empty())
{
res.push_back(pq.top().second);
pq.pop();
}
reverse(res.begin(), res.end());
return res;
}
};