function topKFrequent(nums: number[], k: number): number[] {
const freq = new Map<number, number>();
for (const num of nums) {
freq.set(num, (freq.get(num) ?? 0) + 1);
}
const heap: [number, number][] = [...freq.entries()];
const siftDown = (n: number, i: number): void => {
while (true) {
const left = 2 * i + 1;
const right = 2 * i + 2;
let max = i;
if (left < n && heap[left][1] > heap[max][1]) max = left;
if (right < n && heap[right][1] > heap[max][1]) max = right;
if (max === i) break;
[heap[i], heap[max]] = [heap[max], heap[i]];
i = max;
}
};
for (let i = Math.floor(heap.length / 2) - 1; i >= 0; i--) {
siftDown(heap.length, i);
}
const result: number[] = [];
for (let i = 0; i < k; i++) {
result.push(heap[0][0]);
const last = heap.pop()!;
if (heap.length > 0) {
heap[0] = last;
siftDown(heap.length, 0);
}
}
return result;
}