LeetCode 347 前K个高频元素
LeetCode 347 前K个高频元素
问题描述:
给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
HashMap统计频率+桶排序 O(NlogN)
执行用时:16 ms, 在所有 Java 提交中击败了79.68%的用户
内存消耗:42.5 MB, 在所有 Java 提交中击败了28.18%的用户
class Solution {
public int[] topKFrequent(int[] nums, int k) {
/*统计出现次数*/
Map<Integer, Integer> frequencyForNum = new HashMap<>();
for (int num : nums) {
frequencyForNum.put(num, frequencyForNum.getOrDefault(num, 0) + 1);
}
/*使用桶排序,桶下标对应出现次数*/
List<Integer>[] buckets = new ArrayList[nums.length + 1];
for (int key : frequencyForNum.keySet()) {
int frequency = frequencyForNum.get(key);
if (buckets[frequency] == null) {
buckets[frequency] = new ArrayList<>();
}
buckets[frequency].add(key);
}
List<Integer> topK = new ArrayList<>();
for (int i = buckets.length - 1; i >= 0 && topK.size() < k; i--) {
if (buckets[i] == null) {
continue;
}
if (buckets[i].size() <= (k - topK.size())) {
topK.addAll(buckets[i]);
} else {
topK.addAll(buckets[i].subList(0, k - topK.size()));
}
}
return topK.stream().mapToInt(Integer::valueOf).toArray();
}
}