347. Top K Frequent Elements
来源:互联网 发布:淘宝美工要做些什么 编辑:程序博客网 时间:2024/04/29 13:18
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.
使用unordered_map和priority_queue,时间复杂度O(n*lg(n-k))。
class Solution {public: vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int, int> ump; for(auto num : nums) ump[num]++; vector<int> res; priority_queue<pair<int, int>> pq; for(auto it : ump){ pq.push(make_pair(it.second, it.first)); //pair<first, second>, in priority_queue ths first is frequency, second is number if(pq.size() > ump.size() - k){ res.push_back(pq.top().second); pq.pop(); } } return res; }};
0 0
- 347. Top K Frequent Elements
- 347. Top K Frequent Elements
- 347. Top K Frequent Elements
- 347. Top K Frequent Elements
- 347. Top K Frequent Elements
- 347. Top K Frequent Elements
- 347. Top K Frequent Elements
- 347. Top K Frequent Elements
- 347. Top K Frequent Elements
- 347.Top K Frequent Elements
- 347. Top K Frequent Elements
- 347. Top K Frequent Elements
- 347. Top K Frequent Elements
- 347. Top K Frequent Elements
- 347. Top K Frequent Elements
- 347. Top K Frequent Elements
- 347. Top K Frequent Elements
- 347. Top K Frequent Elements
- MySQL 服务无法启动。服务没有报告任何错误。
- maven安装和eclipse集成
- 控制器向视图传递数据的3种方式
- console功能很好很强大
- Effective Java读书笔记六:方法(38-44)
- 347. Top K Frequent Elements
- 最少乘法次数
- JAVA DecimalFormat格式化Double保留两位小数
- 文章标题
- eclipse使用小技巧
- 重写与重载区别
- 泛型
- Redis报错:ERR Operation against a key holding the wrong kind of value 解决处理
- Codeforces Round #395 (Div. 2) D. Timofey and rectangles