1 题目
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.
2 尝试解
2.1 分析
给定一组字符串,要求返回出现频率最高的K个字符串,如果有频率相同的字符串,则按照字符串顺序返回。
典型的top K问题。首先统计每个字符串出现的频率。然后用一个大小为K的小顶堆存放字符串及其频率,排序规则依据题目所示。如果小顶堆溢出,则删除堆顶元素。最后将小顶堆中剩余元素转化为向量输出即可。
2.2 代码
class Solution {
public:
struct cmp{
bool operator()(pair<int,string>&A,pair<int,string>&B){
return A.first > B.first || (A.first == B.first && A.second < B.second);
}
};
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string,int> count;
priority_queue<pair<int,string>,vector<pair<int,string>>,cmp> sorting;
vector<string> result;
for(auto word : words){
count[word] += 1;
}
unordered_map<string,int>::iterator it = count.begin();
while(it != count.end()){
sorting.push(make_pair(it->second,it->first));
if(sorting.size() > k)
sorting.pop();
it++;
}
while(sorting.size()){
result.push_back(sorting.top().second);
sorting.pop();
}
reverse(result.begin(),result.end());
return result;
}
};
3 标准解
3.1 分析
思路同上。
3.2 代码
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> freq;
for(auto w : words){
freq[w]++;
}
auto comp = [&](const pair<string,int>& a, const pair<string,int>& b) {
return a.second > b.second || (a.second == b.second && a.first < b.first);
};
typedef priority_queue< pair<string,int>, vector<pair<string,int>>, decltype(comp) > my_priority_queue_t;
my_priority_queue_t pq(comp);
for(auto w : freq ){
pq.emplace(w.first, w.second);
if(pq.size()>k) pq.pop();
}
vector<string> output;
while(!pq.empty()){
output.insert(output.begin(), pq.top().first);
pq.pop();
}
return output;
}
};