1function topK(nums, k) {
2 const heap = []; // 小顶堆,维护 k 个最大元素
3 const siftUp = (i) => {
4 while (i > 0 && heap[(i-1)>>1] > heap[i]) {
5 [heap[(i-1)>>1], heap[i]] = [heap[i], heap[(i-1)>>1]];
6 i = (i - 1) >> 1;
7 }
8 };
9 const siftDown = (i) => {
10 const n = heap.length;
11 while (2*i+1 < n) {
12 let c = 2*i+1;
13 if (c+1 < n && heap[c+1] < heap[c]) c++;
14 if (heap[i] <= heap[c]) break;
15 [heap[i], heap[c]] = [heap[c], heap[i]];
16 i = c;
17 }
18 };
19 for (const x of nums) {
20 if (heap.length < k) {
21 heap.push(x); siftUp(heap.length - 1);
22 } else if (x > heap[0]) {
23 heap[0] = x; siftDown(0);
24 }
25 }
26 return heap.sort((a, b) => b - a);
27}