- Top K Frequent Words
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.
1.使用map存储,然后将键值对存到向量,对向量进行排序。
static bool cmp(pair<string,int>a,pair<string,int>b){
if(a.second==b.second){
return a.first<b.first;
}
return a.second>b.second;
}
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string,int>counts;
vector<string>res;
for(int i=0;i<words.size();i++){
counts[words[i]]++;
}
vector<pair<string,int>>v(counts.begin(),counts.end());
sort(v.begin(),v.end(),cmp);
for(int i=0;i<k;i++){
res.push_back(v[i].first);
}
return res;
}
官方题解写的更为精巧,但是提交之后时间和空间的开销都稍大
匿名函数那里我没看懂。。。。。
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string,int>counts;
for(auto x:words){
counts[x]++;
}
vector<string>res(words.size());
for(auto &[key,value]:counts){
res.emplace_back(key);
}
sort(res.begin(),res.end(),[&](const string &a,const string &b)->bool{
return counts[a]>counts[b]||counts[a]==counts[b]&&a<b;
});
res.erase(res.begin()+k,res.end());
return res;
}
2.优先队列
第一次接触优先队列,对堆还很不熟悉
依旧还没看懂。。。。。。
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string,int>counts;
int n=words.size();
for(int i=0;i<n;i++){
counts[words[i]]++;
}
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 : counts) {
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;
}