|
| 1 | +// class MaxHeap { |
| 2 | +// constructor() { |
| 3 | +// this.heap = []; |
| 4 | +// } |
| 5 | + |
| 6 | +// getParentIndex(idx) { |
| 7 | +// return Math.floor((idx - 1) / 2); |
| 8 | +// } |
| 9 | + |
| 10 | +// getRightChildIndex(idx) { |
| 11 | +// return idx * 2 + 2; |
| 12 | +// } |
| 13 | + |
| 14 | +// getLeftChildIndex(idx) { |
| 15 | +// return idx * 2 + 1; |
| 16 | +// } |
| 17 | + |
| 18 | +// hasParent(idx) { |
| 19 | +// return this.getParentIndex(idx) >= 0; |
| 20 | +// } |
| 21 | + |
| 22 | +// size(){ |
| 23 | +// return this.heap.length; |
| 24 | +// } |
| 25 | +// add(val) { |
| 26 | +// this.heap.push(val); |
| 27 | +// this.heapifyUp(); |
| 28 | +// } |
| 29 | + |
| 30 | +// remove() { |
| 31 | +// if (this.heap.length === 0) return null; |
| 32 | + |
| 33 | +// const top = this.heap[0]; |
| 34 | +// this.heap[0] = this.heap[this.heap.length - 1]; |
| 35 | +// this.heap.pop(); |
| 36 | +// this.heapifyDown(); |
| 37 | +// return top; |
| 38 | +// } |
| 39 | + |
| 40 | +// heapifyUp(val) { |
| 41 | +// let idx = this.heap.length - 1; |
| 42 | +// while (this.hasParent(idx)) { |
| 43 | +// let parentIdx = getParentIndex(idx); |
| 44 | +// if (this.heap[idx] > this.heap[parentIdx]) { |
| 45 | +// this.swap(idx, parentIdx); |
| 46 | +// idx = parentIdx; |
| 47 | +// } else { |
| 48 | +// break; |
| 49 | +// } |
| 50 | +// } |
| 51 | +// } |
| 52 | + |
| 53 | +// heapifyDown() { |
| 54 | +// let idx = 0; |
| 55 | +// while (this.getLeftChildIndex(idx) > 0) { |
| 56 | +// let largerIdx = this.getLeftChildIndex(idx); |
| 57 | +// if ( |
| 58 | +// this.getRightChildIndex(idx) < this.heap.length && |
| 59 | +// this.heap[this.getRightChildIndex(idx)] < this.heap[largerIdx] |
| 60 | +// ) { |
| 61 | +// largerIdx = this.getRightChildIndex(idx); |
| 62 | +// } |
| 63 | +// if (this.heap[largerIdx] > this.heap[idx]) { |
| 64 | +// this.swap(largerIdx, idx); |
| 65 | +// idx = largerIdx; |
| 66 | +// } else { |
| 67 | +// break; |
| 68 | +// } |
| 69 | +// } |
| 70 | +// } |
| 71 | + |
| 72 | +// swap(a, b) { |
| 73 | +// [this.heap[a], this.heap[b]] = [this.heap[b], this.heap[a]]; |
| 74 | +// } |
| 75 | +// } |
| 76 | + |
| 77 | +/** |
| 78 | + * @param {number[]} stones |
| 79 | + * @return {number} |
| 80 | + */ |
| 81 | +var lastStoneWeight = function (stones) { |
| 82 | + const maxHeap = new MaxHeap(); |
| 83 | + for (const stone of stones) { |
| 84 | + maxHeap.push(stone); |
| 85 | + } |
| 86 | + |
| 87 | + while (maxHeap.size() > 1) { |
| 88 | + const num1 = maxHeap.pop(); |
| 89 | + const num2 = maxHeap.pop(); |
| 90 | + if (num1 === num2) continue; |
| 91 | + maxHeap.push(Math.abs(num1 - num2)); |
| 92 | + } |
| 93 | + if (maxHeap.size() === 0) return 0; |
| 94 | + return maxHeap.pop(); |
| 95 | +}; |
0 commit comments