题目描述:
Given a non-empty list of words, return the k most frequent elements.
Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.
Example 1:
Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
Output: ["i", "love"]
Explanation: "i" and "love" are the two most frequent words. Note that "i" comes before "love" due to a lower alphabetical order.
Example 2:
Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
Output: ["the", "is", "sunny", "day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.
Note:
1. You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
2. Input words contain only lowercase letters.
Follow up:
1. Try to solve it in O(n log k) time and O(n) extra space.
class comp{
public:
bool operator()(pair<string,int> a, pair<string,int> b)
{ //优先队列中将次数较小的元素置于队首,这样删除的时候也是先删除频率低的元素
if(a.second>b.second) return true;
else if(a.second==b.second&&a.first<b.first) return true;//字典序大的元素排前
else return false;
}
};
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string,int> hash;
for(string word:words)
{
if(hash.count(word)==0) hash[word]=1;
else hash[word]++;
}
priority_queue<pair<string,int>,vector<pair<string,int>>,comp> q;
for(auto x:hash)
{
if(q.size()<k) q.push({x.first,x.second});
else
{
q.push({x.first,x.second});
q.pop();
}
}
vector<string> result;
while(!q.empty())
{
result.push_back(q.top().first);
q.pop();
}
//队首的元素次数较小,需要将result的元素翻转
reverse(result.begin(),result.end());
return result;
}
};
本文介绍了一种算法,用于从非空单词列表中找出出现频率最高的k个单词。算法首先使用哈希表统计每个单词的出现次数,然后通过优先队列(最小堆)保持k个最高频单词。最后,返回按频率降序且字母顺序排列的单词列表。
849

被折叠的 条评论
为什么被折叠?



