参考链接
- https://leetcode-cn.com/problems/top-k-frequent-words/
- https://leetcode-cn.com/problems/top-k-frequent-words/solution/qian-kge-gao-pin-dan-ci-by-leetcode-solu-3qk0/
题目描述
给一非空的单词列表,返回前 k 个出现次数最多的单词。
返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率,按字母顺序排序。
解题思路
两个哈希表
先遍历数组,用一个哈希表存储每个单词的次数,然后遍历这个哈希表,用另一个哈希表建立次数到单词的映射。单词最大出现的次数为数组大小,从最大次数开始,如果存在这个次数,则将对应单词加入结果。
哈希表+排序
遍历数组,用哈希表记录每个单词的次数,然后对每个单词按次数进行排序。
优先队列
优先队列可以在 O(logn) 的时间内完成插入或删除元素的操作(其中 n 为优先队列的大小),并可以 O(1) 地查询优先队列顶端元素。
还是先用哈希表记录每个单词的次数,然后将单词插入优先队列,如果队列大小超过了k,就删除队列头的元素,最后只需要逆序取出优先队列的前k个元素即可。
代码
两个哈希表
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> word2times;
unordered_map<int, set<string>> times2word;
vector<string> res;
for (auto& word : words)
{
word2times[word] ++;
}
for (auto& item : word2times)
{
times2word[item.second].insert(item.first);
}
for (int i = words.size(); i >= 0 && res.size() < k; i --)
{
if (times2word.count(i) != 0)
{
for (auto& word : times2word[i])
{
res.push_back(word);
if (res.size() >= k)
{
break;
}
}
}
}
return res;
}
};
哈希表+排序
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> cnt;
for (auto& word : words) {
++cnt[word];
}
vector<string> rec;
for (auto& [key, value] : cnt) {
rec.emplace_back(key);
}
sort(rec.begin(), rec.end(), [&](const string& a, const string& b) -> bool {
return cnt[a] == cnt[b] ? a < b : cnt[a] > cnt[b];
});
rec.erase(rec.begin() + k, rec.end());
return rec;
}
};
优先队列
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> cnt;
for (auto& word : words) {
cnt[word]++;
}
auto cmp = [](const pair<string, int>& a, const pair<string, int>& b) {
return a.second == b.second ? a.first < b.first : a.second > b.second;
};
priority_queue<pair<string, int>, vector<pair<string, int>>, decltype(cmp)> que(cmp);
for (auto& it : cnt) {
que.emplace(it);
if (que.size() > k) {
que.pop();
}
}
vector<string> ret(k);
for (int i = k - 1; i >= 0; i--) {
ret[i] = que.top().first;
que.pop();
}
return ret;
}
};