Top K Frequent Elements
2016-05-23 18:24
435 查看
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.
思路:
定义一个类 保存一个num的值和频率,并实现比较方法
遍历数组,并用hashMap保存各个数字出现的频率
对hashmap的value集合排序,获取频率最高的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.
思路:
定义一个类 保存一个num的值和频率,并实现比较方法
遍历数组,并用hashMap保存各个数字出现的频率
对hashmap的value集合排序,获取频率最高的k位
public List<Integer> topKFrequent(int[] nums, int k) { List<Integer> res = new ArrayList<Integer>(); Map<Integer,FEntity> map = new HashMap<Integer,FEntity>(); //统计各数字出现的次数 存入hashmap for(int t:nums){ FEntity f; if(map.containsKey(t)){ f = map.get(t); f.frequent++; }else{ f = new FEntity(t, 1); } map.put(t, f); } //对hashmap的value 按照频率进行排序 List<FEntity> values = new ArrayList<FEntity>(); Set<Integer> keys = map.keySet(); for(Integer key:keys){ values.add(map.get(key)); } Collections.sort(values); //统计频率最高的k个数 for(int i=0;i<k;i++){ res.add(values.get(values.size()-1-i).num); } return res; } class FEntity implements Comparable<FEntity> { int num, frequent; public FEntity(int num, int frequent) { this.num = num; this.frequent = frequent; } public int compareTo(FEntity arg0) { if (frequent > arg0.frequent) return 1; else if (frequent == arg0.frequent) return 0; else return -1; } }
相关文章推荐
- uiscrollview contentsize uistoryboard
- 删除用户自定义配置
- 【Leetcode】Repeated DNA Sequences
- 让UITableViewCell的分隔线显示完全
- 21.UITextField
- Request获取用户真实IP
- Sketch设计UI的知识总结
- 动态规划——unique-paths
- 获取Request中Cookie的值
- We are unable to process your request. An unknown error occurred.
- UI配置的代码实现
- UGUI下拉列表的封装
- iOS 8 Auto Layout界面自动布局系列2-使用Xcode的Interface Builder添加布局约束
- Ural 1081 Binary Lexicographic Sequence
- 加速android studio build 速度
- Angular服务Request异步请求的详细分析
- 03.LoT.UI 前后台通用框架分解系列之——多样的表格
- UITextField 的clearButton
- java应用测试报告生成(二):利用ant的build.xml生成测试报告
- iOS学习之——UIStoryboard