-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path692.cpp
More file actions
30 lines (27 loc) · 825 Bytes
/
692.cpp
File metadata and controls
30 lines (27 loc) · 825 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
class Solution {
public:
struct cmp {
bool operator()(const pair<int,string> &a, const pair<int,string> &b) {
return (a.first == b.first) ? (a.second < b.second) : (a.first > b.first);
};
};
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> dict;
for(string s : words) {
dict[s]++;
}
priority_queue<pair<int,string>, vector<pair<int,string>>, cmp> minheap;
for(auto& [s,val]: dict){
minheap.push({val,s});
if(minheap.size()>k)
minheap.pop();
}
vector<string> res(k);
while(!minheap.empty()){
k--;
res[k] = minheap.top().second;
minheap.pop();
}
return res;
}
};