Leetcode 692. Top K Frequent Words

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Top K Frequent Words

2. Solution

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
bool compare(pair<string, int>& a, pair<string, int>& b) {
if(a.second == b.second) {
return a.first < b.first;
}
return a.second > b.second;
}

class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
vector<string> result;
unordered_map<string, int> stat;
for(string word: words) {
stat[word]++;
}
vector<pair<string, int>> values;
for(auto val: stat) {
values.push_back(val);
}
sort(values.begin(), values.end(), compare);
for(int i = 0; i < k; i++) {
result.push_back(values[i].first);
}
return result;
}
};

Reference

  1. https://leetcode.com/problems/top-k-frequent-words/description/
如果有收获,可以请我喝杯咖啡!