LeetCode | 347. Top K Frequent Elements 优先队列技巧题

Givena non-empty array of integers, return the k mostfrequent elements.

Forexample,
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.

这一题要求运行时间为O(n log n),于这种题目,要求你取出现次数最多的k个数,可以使用一个unorder_map统计各个数字出现的次数然后遍历unorder_map,将其中的每一个pair<int,int>反转,放入map<int,int>中或者是priority_queue中,这是因为这两种数据结构到都有自动排序的功能,不同的是map是按照键值从小到大排序,而priority_queues是按照其中的值从大到小排序,值得一提的是,假如priority_queues中存的值是pair<int,int>类型的话,priority_queues中的值会按照pair的key的值从大到 小的顺序排列,这一点要注意

  不过这一题使用priority_queues更加好一些,因为优先队列使用大根堆,其功能单一,而map比较优先级队列多出了更多的功能,其代价就是运行时间的延长,以后在做题的时候,当需要一个数组,将数据一个一个的输入,并且排序,然后输出前n个数,记得使用优先级队列这个数据结构,优先级队列使用的是堆排序,取前n大的数或者是前n小的数其效率是极高的

class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
	vector<int> result;
	unordered_map<int, int> store;
	for (int u: nums)
	{
		store[u]++;
	}
	priority_queue <pair<int, int>> mark;
	for (auto u : store)
	{
		mark.push(pair<int, int>(u.second, u.first));
	}
	for (int i = 0; i < k; i++)
	{
		result.push_back(mark.top().second);
		mark.pop();
	}
	return result;
}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值