Leetcode#347. 前K个高频元素

给定一个非空的整数数组,返回其中出现频率前 高的元素。

例如,

给定数组 [1,1,1,2,2,3] , 和 k = 2,返回 [1,2]

注意:

  • 你可以假设给定的 总是合理的,1 ≤ k ≤ 数组中不相同的元素的个数。
  • 你的算法的时间复杂度必须优于 O(n log 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();
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值