image.png
解法
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> countMap = new HashMap(nums.length);
for (int i : nums) {
countMap.put(i, countMap.getOrDefault(i, 0) + 1);
}
// 小顶堆,第一个元素代表数字,第二个元素代表数字出现的次数
PriorityQueue<int []> pq = new PriorityQueue<int []>(new Comparator<int []> () {
public int compare(int[] n1, int[] n2) {
return n1[1] - n2[1];
}
});
for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {
int val = entry.getKey();
int count = entry.getValue();
if (pq.size() == k) {
// 等于k以后,如果堆顶的数目小于count,出堆
if (pq.peek()[1] < count) {
pq.poll();
pq.offer(new int[]{val, count});
}
} else {
pq.offer(new int[]{val, count});
}
}
int[] ret = new int[k];
int i = 0;
while (pq.size() > 0) {
ret[i] = pq.poll()[0];
i++;
}
return ret;
}
}
网友评论