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号,杂七杂八的事情有些多,耽搁了一段时间。

posted @ 2016-08-22 08:19  Deribs4  阅读(187)  评论(0编辑  收藏  举报