题目传送门
链接:https://leetcode-cn.com/problems/top-k-frequent-words/
题干
题解
又是被leetcode卡到爆的一天,因为不能自定义函数,所以在结构体里写的重载
用map来记录每个单词出现的次数,再按要求进行排序即可
Code
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
map<string, int> mp;
vector<string> res;
struct node {
int num;
string word;
bool operator < (const node &b) const {
if (num != b.num) return num > b.num;
else return word < b.word;
}
};
vector<node> vec;
for (auto s : words) {
mp[s]++;
}
for (auto item : mp) {
vec.push_back({item.second, item.first});
}
sort(vec.begin(), vec.end());
for (int i = 0; i < k; i++) {
res.push_back(vec[i].word);
}
return res;
}
};