Skip to content

Commit 5750dc8

Browse files
committed
Time: 22 ms (24.88%), Space: 12.6 MB (72.76%) - LeetHub
1 parent a558e47 commit 5750dc8

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# define pii pair< int, string >
2+
3+
class Compare {
4+
public:
5+
bool operator()(pii p1, pii p2){
6+
return p1.first > p2.first || (p1.first == p2.first && p1.second < p2.second);
7+
}
8+
};
9+
10+
class Solution {
11+
public:
12+
vector<string> topKFrequent(vector<string>& words, int k) {
13+
unordered_map<string, int> m;
14+
int n = words.size();
15+
int i = 0;
16+
while(i<n){
17+
m[words[i]]++;
18+
i++;
19+
}
20+
vector<string> ans;
21+
priority_queue<pii, vector<pii>, Compare> q;
22+
for(auto p: m){
23+
q.push({p.second, p.first});
24+
if(q.size() > k){
25+
q.pop();
26+
}
27+
}
28+
while(!q.empty()){
29+
ans.insert(ans.begin(), q.top().second);
30+
q.pop();
31+
}
32+
33+
return ans;
34+
}
35+
};

0 commit comments

Comments
 (0)