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 topKFrequent(vector & nums, int k) { 4 unordered_mapum; 5 for(int num:nums){ 6 um[num]++; 7 } 8 vector > bucket(nums.size()+1); 9 for(auto p:um){10 bucket[p.second].push_back(p.first);11 }12 vector res;13 for(int i=bucket.size()-1;i>=0&&res.size()
O(nlog(n-k))的做法:
1 class Solution { 2 public: 3 vector topKFrequent(vector & nums, int k) { 4 unordered_mapum; 5 for(int num:nums){ 6 um[num]++; 7 } 8 vector res; 9 priority_queue > 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号,杂七杂八的事情有些多,耽搁了一段时间。