|
| 1 | +// 😢 |
| 2 | + |
| 3 | +/** |
| 4 | + * @param {number[]} nums |
| 5 | + * @param {number} k |
| 6 | + * @return {number} |
| 7 | + */ |
| 8 | +var findKthLargest = function (nums, k) { |
| 9 | + const heap = new MaxBinaryHeap(); |
| 10 | + |
| 11 | + for (const num of nums) { |
| 12 | + heap.insert(num); |
| 13 | + } |
| 14 | + |
| 15 | + for (let i = 0; i < k; i++) { |
| 16 | + const extractedValue = heap.extractMax(); |
| 17 | + if (i === k - 1) return extractedValue; |
| 18 | + } |
| 19 | +}; |
| 20 | + |
| 21 | +class MaxBinaryHeap { |
| 22 | + constructor() { |
| 23 | + this.values = []; |
| 24 | + } |
| 25 | + |
| 26 | + insert(value) { |
| 27 | + this.values.push(value); |
| 28 | + this.#bubbleUp(); |
| 29 | + |
| 30 | + return this.values; |
| 31 | + } |
| 32 | + |
| 33 | + extractMax() { |
| 34 | + const extractedValue = this.values[0]; |
| 35 | + const poppedValue = this.values.pop(); |
| 36 | + |
| 37 | + if (this.values.length === 0) return extractedValue; |
| 38 | + |
| 39 | + this.values[0] = poppedValue; |
| 40 | + this.#sinkDown(); |
| 41 | + |
| 42 | + return extractedValue; |
| 43 | + } |
| 44 | + |
| 45 | + #bubbleUp() { |
| 46 | + let currentIndex = this.values.length - 1; |
| 47 | + const currentValue = this.values[currentIndex]; |
| 48 | + |
| 49 | + while (currentIndex > 0) { |
| 50 | + const parentIndex = Math.floor((currentIndex - 1) / 2); |
| 51 | + const parentValue = this.values[parentIndex]; |
| 52 | + |
| 53 | + if (parentValue >= currentValue) break; |
| 54 | + |
| 55 | + this.values[parentIndex] = currentValue; |
| 56 | + this.values[currentIndex] = parentValue; |
| 57 | + |
| 58 | + currentIndex = parentIndex; |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + #sinkDown() { |
| 63 | + let currentIndex = 0; |
| 64 | + const currentValue = this.values[currentIndex]; |
| 65 | + const length = this.values.length; |
| 66 | + |
| 67 | + while (true) { |
| 68 | + let leftChildIndex = currentIndex * 2 + 1; |
| 69 | + let rightChildIndex = currentIndex * 2 + 2; |
| 70 | + let leftChildValue, rightChildValue; |
| 71 | + let swapWith = null; |
| 72 | + |
| 73 | + if (leftChildIndex < length) { |
| 74 | + leftChildValue = this.values[leftChildIndex]; |
| 75 | + if (leftChildValue > currentValue) swapWith = leftChildIndex; |
| 76 | + } |
| 77 | + |
| 78 | + if (rightChildIndex < length) { |
| 79 | + rightChildValue = this.values[rightChildIndex]; |
| 80 | + if ( |
| 81 | + (!swapWith && rightChildValue > currentValue) || |
| 82 | + (swapWith && rightChildValue > leftChildValue) |
| 83 | + ) { |
| 84 | + swapWith = rightChildIndex; |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + if (!swapWith) break; |
| 89 | + |
| 90 | + this.values[currentIndex] = this.values[swapWith]; |
| 91 | + this.values[swapWith] = currentValue; |
| 92 | + |
| 93 | + currentIndex = swapWith; |
| 94 | + } |
| 95 | + } |
| 96 | +} |
0 commit comments