Total Accepted: 2605
Total Submissions: 5933
Difficulty: Medium
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.
分析:
两个核心操作,
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;
};
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/51317106
原作者博客:http://blog.csdn.net/ebowtang
本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895