-
Notifications
You must be signed in to change notification settings - Fork 5
/
LC_692_TopKFrequentWords.cpp
70 lines (51 loc) · 1.61 KB
/
LC_692_TopKFrequentWords.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
https://leetcode.com/problems/top-k-frequent-words/
692. Top K Frequent Words
*/
struct Comparator_2{
bool operator()(pair<int,string> &a, pair<int, string> &b)
{
if(a.first == b.first)
return a.second > b.second;
return a.first < b.first;
}
};
class Solution {
public:
vector<string> topKFrequent_2(vector<string>& words, int k) {
vector<string> ans;
priority_queue<pair<int,string>, vector<pair<int,string>>, Comparator_2> pq;
unordered_map<string, int> freq;
for(string s: words)
freq[s]++;
for(auto x: freq)
pq.push({x.second, x.first});
while(k--) {
// cout<<pq.top().second<<" "<<pq.top().first<<endl;
ans.push_back(pq.top().second);
pq.pop();
}
return ans;
}
static bool mycmp(pair<int,string> &a, pair<int, string> &b)
{
if(a.first == b.first)
return a.second < b.second;
return a.first > b.first;
}
vector<string> topKFrequent(vector<string>& words, int k) {
vector<string> ans;
vector<pair<int,string>> vec;
unordered_map<string, int> freq;
for(string s: words)
freq[s]++;
for(auto x: freq)
vec.push_back({x.second, x.first});
sort(vec.begin(), vec.end(), mycmp);
int i=0;
while(k-- && i<vec.size()) {
ans.push_back(vec[i++].second);
}
return ans;
}
};