思路
这道题还是使用优先队列,是要大根堆,然后创建一个类,成员变量值和次数。大根堆基于次数排序。前k个就拿出前k的类的值即可。代码如下:
class Solution {
public int[] topKFrequent(int[] nums, int k) {
if (nums == null || nums.length == 0 || k < 1 || k > nums.length) {
return null;
}
int[] ans = new int[k];
PriorityQueue<Info> priorityQueue = new PriorityQueue<>((o1, o2) -> o2.times - o1.times);
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
if (map.containsKey(num)) {
map.put(num, map.get(num) + 1);
} else {
map.put(num, 1);
}
}
map.forEach((value, times) -> {
Info info = new Info();
info.times = times;
info.value = value;
priorityQueue.add(info);
});
for (int i = 0; i < k; i++) {
ans[i] = priorityQueue.poll().value;
}
return ans;
}
class Info {
public int times;
public int value;
public Info() {
}
}
}