_bubbleUp(){
// access the value at the end
// reorganize the heap
let currentIndex = this.size() - 1
while(this._compare(currentIndex, this._parent(currentIndex))){
this._swap(currentIndex, this._parent(currentIndex))
currentIndex = this._parent(currentIndex)
}
}
We want to run a simulation on the stones as follows:
Continue the simulation until there is no more than one stone remaining.
Return the weight of the last remaining stone or return 0 if none remain.
Example 1:
Explanation:
We smash 6 and 4 and are left with a 2, so the array becomes [2,3,2,2].
We smash 3 and 2 and are left with a 1, so the array becomes [1,2,2].
We smash 2 and 2, so the array becomes [1].
Example 2:
Constraints:
where stone are organizedw 6 4 3 2 2 1st heavy = 64 2 3 2 2nd heavy = 43 2 2 3rd heavy = 32 2 4rth heavy = 22 5th heavy = 2We need to organise our stones based on their weight:
difference = 1stHeavy - 2nd heavy = 6 - 4 = 2 once we calculate the difference we need to insert it back heap.insert(difference)Implementing Max Heap
lass Solution { /** * @param {number[]} stones * @return {number} */ lastStoneWeight(stones) { let heap = new Heap() for(let stone of stones){ heap.insert(stone) } while(1 < heap.size()){ let heaviest = heap.pop() let heavier = heap.pop() let diff = heaviest - heavier heap.insert(diff) } return heap.pop() }lass Heap{ constructor(comparator = (a, b) => b < a){ this.comparator = comparator this._heap = [] } _parent(node){ return Math.floor((node -1) / 2) } _leftChild(node){ return node * 2 + 1 } _rightChild(node){ return node * 2 + 2 } _swap(i, j){ let temp = this._heap[i] this._heap[i] = this._heap[j] this._heap[j] = temp } size(){ return this._heap.length } _compare(i, j){ return this.comparator(this._heap[i], this._heap[j]) }_bubbleUp(){ // access the value at the end // reorganize the heap let currentIndex = this.size() - 1 while(this._compare(currentIndex, this._parent(currentIndex))){ this._swap(currentIndex, this._parent(currentIndex)) currentIndex = this._parent(currentIndex) } }insert(node){ this._heap.push(node) this._bubbleUp() } peek(){ return this._heap[0] }removing 45
reorganizing the heap i.e bubbleDown
_bubbleDown(){ let parentIndex = 0 while(true){ let greaterIndex = parentIndex let leftChildIndex = this._leftChild(parentIndex) let rightChildIndex = this._rightChild(parentIndex) if(this._compare(leftChildIndex, greaterIndex)){ greaterIndex = leftChildIndex } if(this._compare(rightChildIndex, greaterIndex)){ greaterIndex = rightChildIndex } if(greaterIndex === parentIndex){ break } this._swap(greaterIndex, parentIndex) parentIndex = greaterIndex } }pop(){ this._swap(0, this.size() - 1 ) const result = this._heap.pop() this._bubbleDown() return result } }#Heap #dataStructure #priorityQueues