给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
例如,
给定数组 [1,1,1,2,2,3]
, 和 k = 2,返回 [1,2]
。
注意:
- 你可以假设给定的 k 总是合理的,1 ≤ k ≤ 数组中不相同的元素的个数。
- 你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。
解题思路:
先用hash方式统计每个数字的出现频率,而后建立一个长度为k的优先队列(小顶堆),保留出现频率最高的k个元素。
#include<iostream>
#include<string>
#include<queue>
#include<algorithm>
#include<unordered_map>
#include<assert.h>
#include<functional>
using namespace std;
typedef pair<int, int> PP;
// 时间复杂度O(nlogk)
//空间复杂度为O(k)
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> vis;//map<元素,频率>
for (int i = 0; i<nums.size(); ++i){
vis[nums[i]]++;
}
assert(k <= vis.size());
priority_queue<PP, vector<PP>, greater<PP>> topk_heap;//建立长度为k的小顶堆,PP<频率,元素>
for (auto v : vis){
if (topk_heap.size() == k){//如果当前的堆已经到达最大长度
if (v.second > topk_heap.top().first){//若果当前遍历的hash值大于小顶堆堆顶元素的值,则替换
topk_heap.pop();
topk_heap.push(make_pair(v.second, v.first));
}
}
else{
topk_heap.push(make_pair(v.second, v.first));
}
}
vector<int> res;
while (!topk_heap.empty()){
res.push_back(topk_heap.top().second);
topk_heap.pop();
}
return res;
}
void test_topKFrequent(){
vector<int> nums = { 1, 2, 2, 2, 2, 3, 4, 6, 4, 6, 7, 5, 3, 2, 2, 2, 3, 4, 7, 8, 7, 7, 7, 6, 6, 5 };
vector<int> result= topKFrequent(nums,3);
for (auto re : result){
cout << re << " ";
}
cout << endl;
}
int main(){
test_topKFrequent();
getchar();
}