【LeetCode】347. Top K Frequent Elements

347. Top K Frequent Elements

Description:
Given a non-empty array of integers, return the k most frequent elements.
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.
Difficulty:Medium
Example:

Input:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
方法1: 优先队列
  • Time complexity : O ( n l o g ( n − k ) ) O\left ( nlog(n-k) \right ) O(nlog(nk))
  • Space complexity : O ( n ) O\left ( n\right ) O(n)
    思路:
    首先HsahMap存储频率,再利用priority_queue数据结构将pair<frequent, num>存储起来,维护一个n-k的heap,priority_queue的底层是用heap实现的。
   //默认是大顶堆
    priority_queue<int> a; 
    //等同于 priority_queue<int, vector<int>, less<int> > a;
    
    //小顶堆,这里一定要有空格,不然成了右移运算符↓
    priority_queue<int, vector<int>, greater<int> > c;  
class Solution {
public:
	vector<int> topKFrequent(vector<int>& nums, int k) {
		vector<int> res;
		unordered_map<int, int> map;
		for (auto num : nums)
			map[num]++;
		priority_queue<pair<int, int>> pq;
		for (auto ite = map.begin(); ite != map.end(); ite++) {
			pq.push(make_pair(ite->second, ite->first));
			if (pq.size() > map.size() - k) {
				res.push_back(pq.top().second);
				pq.pop();
			}
		}
		return res;
	}
};
方法2: 桶排序
  • Time complexity : O ( n ) O\left ( n \right ) O(n)
  • Space complexity : O ( n ) O\left ( n\right ) O(n)
    思路:
    首先HsahMap存储频率,再将map中的value作为index,key作为value转成二维数组,从未到头遍历,直至找到k个。
class Solution {
public:
	vector<int> topKFrequent(vector<int>& nums, int k) {
		vector<int> res;
		unordered_map<int, int> map;
		for (auto num : nums)
			map[num]++;
        vector<vector<int>> buckets(nums.size()+1);
        for (auto m : map)
            buckets[m.second].push_back(m.first);
        for (int i = buckets.size()-1; i >= 0; i--){
            for (auto j : buckets[i]){
                res.push_back(j);
                if(res.size() == k)
                    return res;
            }
        }
		return res;
	}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值