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].
算法
O(nlgn)
两个核心操作,
1,利用哈希map统计频次及其对应数字
2,根据频次(及其对应数字)建立最大堆,然后我们总是弹出堆顶就能获取当前最大频次
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
//一,统计处频次
unordered_map<int,int> mapping;
for(int number : nums)
mapping[number]++;
//二,根据频次压入最大堆中
// pair<first, second>: first is frequency, second is number
priority_queue<pair<int,int>> pri_que; //最大堆
for(auto it = mapping.begin(); it != mapping.end(); it++)
pri_que.push(make_pair(it->second, it->first));
//三,获取结果
while(result.size() < k){
result.push_back(pri_que.top().second);
pri_que.pop();
}
return result;
}
private:
vector<int> result;
};