347. Top K Frequent Elements
2016-07-12 16:29
537 查看
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.
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.
class Solution { public: vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int, int> m; for (int n : nums){ m ++; } priority_queue<pair<int, int>> pq; for (auto n:m){ pq.push(make_pair(n.second, n.first)); } vector<int> res(k); for (int i = 0; i < k; i++){ res[i] = pq.top().second; pq.pop(); } return res; } };
相关文章推荐
- android -- 蓝牙 bluetooth (四)OPP文件传输
- android -- 蓝牙 bluetooth (三)搜索蓝牙
- UE4使用widget创建UI界面播放视频
- u3d第一发使用ugui完成消灭星星游戏(一)
- UE4使用widget创建UI界面播放视频
- 【UESTC 482】Charitable Exchange(优先队列+bfs)
- iOS UITextView相关
- bigbluebutton视频直播服务器调用接口
- SAP OBYC自动记账的实例说明 +VALUE STRING
- requestLayout, invalidate 和 postInvalidate 的异同
- android -- 蓝牙 bluetooth (二) 打开蓝牙
- web项目开发上传功能
- JUC源码分析21-队列-LinkedBlockingDeque
- iOS如果给UITapGestureRecognizer添加tap值
- hdu 3530 Subsequence 单调队列
- NDK 编译报错:request for member 'FindClass' in something not a structure or union
- OC_UIColor 类扩展支持十六进制
- iOS开发 ☞ 对比学习UIView动画
- iOS子线程更新UI的两种方法
- iOS7-9。获取iOS设备uuid