跳到主要内容

LeetCode:215. 数组中的第K个最大元素

使用最小堆方法

/**
* JavaScript 实现:最小堆类
* 插入
* 删除
* 返回堆头
* 返回堆长
*/

class MinHeap {
constructor() {
this.heap = []
}

swap(i1, i2) {
// 交换两个值
const temp = this.heap[i1]
this.heap[i1] = this.heap[i2]
this.heap[i2] = temp
}

getParentIndex(i) {
// 获取父元素的索引值 (index-1)/2
// 类似 Math.floor((index-1/2))
return (i - 1) >> 1
}

getLeftIndex(i) {
// 获取左元素的索引值 i*2+1
// 类似 Math.floor((index-1/2))
return i * 2 + 1
}

getRightIndex(i) {
// 获取右元素的索引值 i*2+2
// 类似 Math.floor((index-1/2))
return i * 2 + 2
}

shiftUp(index) {
if (index === 0) return;

const parentIndex = this.getParentIndex(index)

// 较小的值 上移
if (this.heap[index] < this.heap[parentIndex]) {
this.swap(index, parentIndex)
this.shiftUp(parentIndex)
}
}

shiftDown(index) {
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()
}

console.log(heap)
})

return heap.peek()
};