【leetcode】Top K Frequent Elements
2016-05-31 11:53
225 查看
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.
利用桶排序,分三步解决,时间代价O(n):
统计每个数的出现频率,存在unordered_map中
定义一个vector<vector<int>>容器,将每个频率对应的数存在vector中
倒序遍历容器,依次将k个数存入结果容器中
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):
统计每个数的出现频率,存在unordered_map中
定义一个vector<vector<int>>容器,将每个频率对应的数存在vector中
倒序遍历容器,依次将k个数存入结果容器中
class Solution { public: vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int, int> dict; vector<int> result; for (auto n : nums) ++dict ; vector< vector<int> > freq(nums.size() + 1); for (auto p : dict) freq[p.second].push_back(p.first); for (int i = freq.size() - 1; i >= 0 && result.size() < k; --i) { for (auto n : freq[i]) { result.push_back(n); if (result.size() == k) break; } } return result; } };
相关文章推荐
- leetcode Longest Increasing Subsequence
- apue第三版学习环境的配置
- iOS开发 UICollectionView属性介绍
- UICollectionView基础
- sudo: /usr/bin/sudo must be owned by uid 0 and have the setuid bit set
- iOS开发--GPUImage的使用
- duilib CTextUI 纯字母不能换行
- Arduino 和LCD1602液晶屏 I2C接口实验
- iOS学习应用开发就业课_004:UIButton时间处理
- 关于Linkedlist 和 ArrayDeque的讨论
- iOS监听UITabBar的Tab点击事件
- 347. Top K Frequent Elements
- iOS自定义UITableViewCell registerNib: 与 registerClass: 的区别
- Mirantis OpenStack Fuel8.0离线安装(MOS8.0本地源)
- iOS学习应用开发就业课_003:UIButton基本功能
- iOS开发:UITableView加载多张照片导致内存上涨的问题
- UITextField点击选中文字
- java.sql.SQLException: Connections could not be acquired from the underlying database!
- C#里System.Data.SQLite中对GUID的处理
- 实现placeholder属性的UITextView