题目
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3]
and k = 2, return [1,2]
.
Note:
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
分析
使用map统计词频,然后对map中元素进行排序,输出前k个,但是由于sort算法无法直接对map排序,所以要么重定义比较操作,将map转换为vector<pair>进行排序,要么用优先级队列构造最大堆,输出顶部的k个元素。
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k)
{
vector<int> v;
unordered_map<int, int> count_map;
for(auto n: nums) count_map[n]++;
priority_queue<pair<int, int>> maxHeap;//构造优先级队列
for(auto& pair: count_map) maxHeap.emplace(pair.second, pair.first);//以出现频率作为优先级,放置到优先级队列中,优先级高的在队首
while(k--)
{
v.push_back(maxHeap.top().second);//返回前k个队首元素
maxHeap.pop();
}
return v;
}
};
其余的算法参考 Five efficient solutions in C++, well-explained