https://leetcode.com/problems/top-k-frequent-elements/description/
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.
题目为统计出现频率最高的K个元素,思路为以词频为下标,value为值,建立桶数组,最后从末尾取不为null值的k个桶数组的值,即为答案。
public static List<Integer> topKFrequent(int[] nums, int k) {
HashMap<Integer,Integer> freMap = new HashMap<>();
for(int num:nums){
freMap.put(num,freMap.getOrDefault(num,0)+1);//统计词频
}
List<Integer>[] bucket = new List[nums.length+1];//需要用list数组,不能用int[]统计,不然无法handle[1,2]这样两个词频都为1的情况
for(int n:freMap.keySet()){
if(bucket[freMap.get(n)] == null){
bucket[freMap.get(n)] = new ArrayList<>();
}
bucket[freMap.get(n)].add(n);//建立以词频为下标的桶数组list
}
List<Integer> result = new ArrayList<>();
for(int i = bucket.length -1 ; i >= 0&&result.size()<k;i--){
if(bucket[i]!=null){//以result.size()为标准,k个
result.addAll(bucket[i]);
}
}
return result;
}