692. Top K Frequent Words
Medium
77671FavoriteShare
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.
class Solution {
public:
inline bool Cmp1(const pair<int,string>& a1,const pair<int,string>& a2){
if(a1.first > a2.first){
return true;
}
if(a1.first == a2.first && a1.second < a2.second){
return true;
}
return false;
}
struct Cmp{
bool operator ()(const pair<int,string>& a1,const pair<int,string>& a2){
if(a1.first > a2.first){
return true;
}
if((a1.first == a2.first) && (a1.second < a2.second)){
return true;
}
return false;
}
};
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string,int> HashMap;
priority_queue<pair<int,string>,vector<pair<int,string>>,Cmp> Q;
vector<string> Result;
int cnt = 0;
for(auto word : words){
HashMap[word] ++;
}
for(auto i : HashMap){
pair<int,string> tmp= make_pair(i.second,i.first);
if(cnt < k){
Q.push(tmp);
cnt++;
}
else{
if(Cmp1(tmp,Q.top())){
Q.push(tmp);
Q.pop();
}
}
}
while(!Q.empty()){
pair<int,string> tmp = Q.top();
Result.push_back(tmp.second);
Q.pop();
}
reverse(Result.begin(),Result.end());
return Result;
}
};
标签:return,--,a1,队列,a2,TopK,words,pair,first From: https://blog.51cto.com/u_13121994/5798504