1046. 最后一块石头的重量 发表于 2021-03-21 | 分类于 leetcode 简单题 用时:10min 一道简单题应该不会让我手写最大堆吧 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172const swap = function (arr,i,j) { [arr[i],arr[j]] = [arr[j],arr[i]]}class MaxHeap { constructor() { this.count = 0 this.data = new Array(this.count + 1) } shiftUp(k) { // 把新的元素往上排 while(k>=1) { let father = Math.floor(k / 2) if (this.data[k] > this.data[father]) { swap(this.data,k,father) k = father } else { break } } } shiftDown(k) { while( k * 2 <= this.count) { // 表示k 有孩子 let j = k if (k * 2 + 1 <= this.count && this.data[k * 2 + 1] > this.data[k] && this.data[k * 2 + 1] > this.data[k * 2]) { j = k * 2 + 1 } else if (this.data[k * 2] > this.data[k]) { j = k * 2 } else { break } swap(this.data,j,k) k = j } } size() { return this.count } isEmpty() { return this.count === 0 } insert(item) { this.data[++this.count] = item this.shiftUp(this.count) } extractMax() { if (this.count < 0) return let ret = this.data[1] swap(this.data,1,this.count--) this.shiftDown(1) return ret }}var lastStoneWeight = function(stones) { var heap = new MaxHeap() for(let i = 0 ; i < stones.length ; i++) { heap.insert(stones[i]) } while(heap.size() > 1) { var s1 = heap.extractMax() var s2 = heap.extractMax() var reduce = Math.abs(s1 - s2) if (reduce) { heap.insert(reduce) } } if (heap.size() === 0) { return 0 } return heap.extractMax()};