给定整数数组 nums 和整数 k,请返回数组中第 k 个最大的元素。
请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
你必须设计并实现时间复杂度为 O(n) 的算法解决此问题。
思路
class MinHeap { constructor() { this.heap = []; } swap(i1, i2) { const temp = this.heap[i1]; this.heap[i1] = this.heap[i2]; this.heap[i2] = temp; } getParentIndex(index) { return Math.floor((index - 1) / 2); } getLeftIndex(index) { return index * 2 + 1; } getRightIndex(index) { return index * 2 + 2; } shiftUp(index) { if (index === 0) return const parentIndex = this.getParentIndex(index); if (this.heap[parentIndex] > this.heap[index]) { this.swap(index, parentIndex); this.shiftUp(parentIndex) } } shiftDown(index) { if (index === this.heap.length - 1) return; const leftIndex = this.getLeftIndex(index); const rightIndex = this.getRightIndex(index); if (this.heap[index] > this.heap[leftIndex]) { this.swap(index, leftIndex); this.shiftDown(leftIndex); } if (this.heap[index] > this.heap[rightIndex]) { this.swap(index, rightIndex); this.shiftDown(rightIndex); } } insert(val) { this.heap.push(val); this.shiftUp(this.heap.length - 1); } pop() { this.heap[0] = this.heap.pop(); this.shiftDown(0); } peek() { return this.heap[0]; } size() { return this.heap.length; } } /** * @param {number[]} nums * @param {number} k * @return {number} */ var findKthLargest = function(nums, k) { const heap = new MinHeap() nums.forEach( n => { heap.insert(n); if(heap.size() > k) { heap.pop() } }) return heap.peek() };