-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtop_k_frequent_words.cpp
59 lines (43 loc) · 1.17 KB
/
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
51
52
53
54
55
56
57
58
59
/*
Hashmap :
priority queue with custom comparator
*/
class Solution {
public:
struct comp{
bool operator() (const pair<int,string>& a, const 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) {
map<string,int> frequencyMap;
vector<string> result;
for(auto &s: words)
{
if(frequencyMap.count(s)>0)
{
frequencyMap[s] = frequencyMap[s] + 1 ;
}
else
{
frequencyMap[s]=1;
}
}
priority_queue<pair<int,string>,vector<pair<int,string>>,comp> pq;
for(auto &p: frequencyMap)
{
pq.push({p.second,p.first});
}
for(int i =0;i<k;i++)
{
auto s = pq.top();
pq.pop();
result.push_back(s.second);
}
return result;
}
};