给定一个单词列表
words
和一个整数k
,返回前k
个出现次数最多的单词。返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率, 按字典顺序 排序。
示例 1:
输入: words = ["i", "love", "leetcode", "i", "love", "coding"], k = 2 输出: ["i", "love"] 解析: "i" 和 "love" 为出现次数最多的两个单词,均为2次。 注意,按字母顺序 "i" 在 "love" 之前。示例 2:
输入: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4 输出: ["the", "is", "sunny", "day"] 解析: "the", "is", "sunny" 和 "day" 是出现次数最多的四个单词, 出现次数依次为 4, 3, 2 和 1 次。
我们需要提取频次最高的前K个元素,那么就选择维护一个 K容量大小的小跟堆 小根堆就需要在仿函数里面对频次大的条件下返回True ,当频次相同的时候要选择字典序返回,这时候又需要满足一个大根堆的形式,让字典序考后的放在堆的最上面。
最终k容量的堆里面存放就是频次最高的前k个元素,堆顶元素为这k个元素中频次最小,不断从后往前pop出堆,然后放回res返回结果中。
struct Com {
typedef pair<string, int> Node;
bool operator()(const Node& left,const Node& right)
{
仿函数 用于创建优先级队列
if (left.second == right.second)
return left.first < right.first;
return (left.second > right.second)
}
};
class Solution {
public:
typedef pair<string, int> Node;
vector<string> topKFrequent(vector<string>& words, int k) {
map<string, int> dict;
for (auto& e : words)
dict[e]++;
priority_queue<Node, vector<Node>, Com> heap;
for (auto& e : dict)
{
heap.push(e);
if (heap.size() > k)
heap.pop();
}
// vector<string> res;
// while (!heap.empty())
// {
// res.push_back(heap.top().first);
// heap.pop();
// }
// reverse(res.begin(), res.end());
vector<string> res(k);
for(int i = k-1; i >= 0; i--)
{
res[i] = heap.top().first;
heap.pop();
}
return res;
}
};