Top K Frequent Elements
2016-05-11 10:18
330 查看
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given
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.
map加最小堆。
需要新定义比较方法。
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.
map加最小堆。
需要新定义比较方法。
class Solution { struct cmp { bool operator() (const pair<int,int> &a, const pair<int,int> &b) { return a.second>b.second; } }; public: vector<int> topKFrequent(vector<int>& nums, int k) { vector<int> ret; unordered_map<int ,int > Hash; for(int i=0; i<nums.size(); ++i){ Hash[nums[i]]++; } priority_queue<pair<int ,int>,vector<pair<int,int>>,cmp> PQ; for(auto i = Hash.begin(); i != Hash.end(); ++i){ if(PQ.size()!=k){ PQ.push(*i); } else{ if(i->second>PQ.top().second){ PQ.pop(); PQ.push(*i); } } } while(!PQ.empty()){ ret.push_back(PQ.top().first); PQ.pop(); } reverse(ret.begin(),ret.end()); return ret; } };stl库中有partial_sort实质上也是用堆排序完成的。
相关文章推荐
- UGUI实现的变速摇杆
- iOS获取UUID,并使用keychain存储
- setValue:forUndefinedKey
- JBAS011006 Not installing optional component StandardServletAsyncWebRequest due
- hdu 1159 Common Subsequence
- UGUI实现的变速摇杆 (转)
- poj3368 Frequent values(成段更新+离散化求最值)
- MSBuild编译vs工程的常用指令
- iOS开发之基础视图——UITextView
- ROS_Kinetic_02 ROS Kinetic 迁移指南及中文wiki指南(Migration guide)
- ROS_Kinetic_02 ROS Kinetic 迁移指南及中文wiki指南(Migration guide)
- ROS_Kinetic_02 ROS Kinetic 迁移指南及中文wiki指南(Migration guide)
- iOS基础教程:iOS-UI-CoreData学习笔记
- requireJs的使用,以canvas绘制星空为例
- Field 'id' doesn't have a default value 对于SSH 架构,解决起来就简单多了
- CodeForces 286C Main Sequence
- QT中如何使用.ui文件
- bzoj3917【Baltic2014】sequence
- [LeetCode] 347. Top K Frequent Elements 解题思路 - Java
- ui-router