该题与LeetCode215题十分类似
B站视频地址:【LeetCode215_数组中的第K个最大元素_排序_堆排序_非递归写法】 LeetCode215_数组中的第K个最大元素_排序_堆排序_非递归写法
class Solution {
Map<Integer, Integer> map = new HashMap<>();
public int[] topKFrequent(int[] nums, int k) {
int length = nums.length;
for (int i = 0; i < length; i++) {
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
}
int[] heap = new int[k];
int count = 0;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (count < k) {
heap[count] = entry.getKey();
}
count++;
if (count == k) {
buildMinHeap(heap);
}
if (count > k) {
// 调整小根堆
if (entry.getValue() > map.get(heap[0])) {
heap[0] = entry.getKey();
heapAdjust(heap, 0, k);
}
}
}
return heap;
}
public void buildMinHeap(int[] heap) {
int len = heap.length;
for (int i = len / 2 - 1; i >= 0; i--) {
heapAdjust(heap, i, len);
}
}
public void heapAdjust(int[] heap, int root, int heapLen) {
int temp = heap[root];
for (int i = (root << 1) + 1; i < heapLen; i = (i << 1) + 1) {
if (i < heapLen - 1 && map.get(heap[i]) > map.get(heap[i + 1])) {
i++;
}
if (map.get(temp) <= map.get(heap[i])) {
break;
}
heap[root] = heap[i];
root = i;
}
heap[root] = temp;
}
public void swap(int[] heap, int a, int b) {
if (heap[a] != heap[b]) {
int temp = heap[a];
heap[a] = heap[b];
heap[b] = temp;
}
}
}