leetcode 347. Top K Frequent Elements

347. Top K Frequent Elements

  • Total Accepted: 26456
  • Total Submissions: 60329
  • 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.

 

 

思路:最好的是桶排序,牺牲了内存,加快了速度。总的来说,可以有O(n)和O(nlog(n-k))两种做法。

 

代码:

O(n)的做法:

 1 class Solution {
 2 public:
 3     vector<int> topKFrequent(vector<int>& nums, int k) {
 4         unordered_map<int,int> um;
 5         for(int num:nums){
 6             um[num]++;
 7         }
 8         vector<vector<int> > bucket(nums.size()+1);
 9         for(auto p:um){
10             bucket[p.second].push_back(p.first);
11         }
12         vector<int> res;
13         for(int i=bucket.size()-1;i>=0&&res.size()<k;i--){
14             for(int num:bucket[i]){
15                 res.push_back(num);
16                 if(res.size()==k){
17                     break;
18                 }
19             }
20         }
21         return res;
22     }
23 };

 

O(nlog(n-k))的做法:

 1 class Solution {
 2 public:
 3     vector<int> topKFrequent(vector<int>& nums, int k) {
 4         unordered_map<int,int> um;
 5         for(int num:nums){
 6             um[num]++;
 7         }
 8         vector<int> res;
 9         priority_queue<pair<int,int> > pq;
10         for(auto it=um.begin();it!=um.end();it++){
11             pq.push(make_pair(it->second,it->first));
12             if(pq.size()>um.size()-k){//抽屉原理
13                 res.push_back(pq.top().second);
14                 pq.pop();
15             }
16         }
17         return res;
18     }
19 };

 

11号到22号,杂七杂八的事情有些多,耽搁了一段时间。

转载于:https://www.cnblogs.com/Deribs4/p/5794254.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值