LeetCode:Top K Frequent Elements
2016-05-19 09:54
471 查看
Top K Frequent Elements
Total Accepted: 5045 Total
Submissions: 11511 Difficulty: Medium
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.
Subscribe to see which companies asked this question
Hide Tags
Hash Table Heap
Hide Similar Problems
(M) Word Frequency (M)
Kth Largest Element in an Array
思路:桶排序
有6个数:1 1 1 2 2 3
key:0 1 2 3 4 5 6
val:0 3 2 1 0 0 0
其中:val代表key出现的频数。
根据频数大小:
key:1 2 3
val:3 2 1
其中key代表频数,val代表频数对应的数
java code:
public class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
int len = nums.length;
List<Integer>[] bucket = new List[len+1];
for(int num:nums) {
map.put(num, map.getOrDefault(num, 0)+1);
}
for(int key:map.keySet()) {
int value = map.get(key);
if(null == bucket[value]) bucket[value] = new ArrayList<Integer>();
bucket[value].add(key);
}
List<Integer> res = new ArrayList<Integer>();
for(int i=bucket.length-1;i>=0 && res.size()<k;i--) {
if(bucket[i] != null) {
res.addAll(bucket[i]);
}
}
return res;
}
}
相关文章推荐
- Android视图重绘,使用invalidate还是requestLayout
- codeforces_667C. Reberland Linguistics(dp+set)
- Maven项目报"Dynamic Web Module 3.0 requires Java 1.6 or newer."异常的处理办法
- StringBuilder的实现与技巧
- BluetoothAdapter.LeScanCallback
- NanUI for Winform发布,让Winform界面设计拥有无限可能
- StringBuffer 与StringBuilder 区别
- UE4:本地化弹出框
- PropertyValuesHolder实现机制
- ValueAnimator实现机制_源码分析
- window运行gradle build -- --stacktrace出现找不到文件framework-4.3.0.BUILD-SNAPSHOT-schema.zip异常
- hdu 1159Common Subsequence(dp 最大不连续的子序列)
- android Activity runOnUiThread() 方法使用
- UICollectionView-网格视图
- 02.LoT.UI 前后台通用框架分解系列之——灵活的菜单栏
- AdapterView.AdapterContextMenuInfo
- 01.LoT.UI 前后台通用框架分解系列之——小图片背景全屏显示(可自动切换背景)
- complex类 序列化时 IsRequired = true 问题
- Android异步更新UI的四种方式
- 更换证书后 打包异常 "UUID not found"/ "xxxx描述文件 not found"