文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
Top K Frequent Words2. Solution
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;
}
};
网友评论