前一篇博客最小栈,错误以为使用最小堆来实现,写完才发现题目不太对 手写一下最小堆,来复习一下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 var MinHeap = function ( ) { this .minHeap = []; }; MinHeap .prototype .getLeftIdx = function (idx ) { return idx * 2 + 1 ; }; MinHeap .prototype .getRightIdx = function (idx ) { return idx * 2 + 2 ; }; MinHeap .prototype .getParentIdx = function (idx ) { return Math .floor ((idx - 1 ) / 2 ); }; MinHeap .prototype .heapifyUp = function ( ) { const length = this .minHeap .length ; let curIdx = length - 1 , parentIdx = this .getParentIdx (curIdx); while (parentIdx >= 0 && this .minHeap [curIdx] < this .minHeap [parentIdx]) { const temp = this .minHeap [curIdx]; this .minHeap [curIdx] = this .minHeap [parentIdx]; this .minHeap [parentIdx] = temp; curIdx = parentIdx; parentIdx = this .getParentIdx (curIdx); } }; MinHeap .prototype .heapifyDown = function ( ) { let curIdx = 0 ; const length = this .minHeap .length ; while (true ) { let leftIdx = this .getLeftIdx (curIdx); let rightIdx = this .getRightIdx (curIdx); let minIdx = curIdx; if (leftIdx < length && this .minHeap [leftIdx] < this .minHeap [minIdx]) { minIdx = leftIdx; } if (rightIdx < length && this .minHeap [rightIdx] < this .minHeap [minIdx]) { minIdx = rightIdx; } if (minIdx === curIdx) { break ; } else { const temp = this .minHeap [curIdx]; this .minHeap [curIdx] = this .minHeap [minIdx]; this .minHeap [minIdx] = temp; curIdx = minIdx; } } }; MinHeap .prototype .push = function (val ) { this .minHeap .push (val); this .heapifyUp (); }; MinHeap .prototype .getMin = function ( ) { if (this .minHeap .length === 0 ) return null ; else if (this .minHeap .length === 1 ) return this .minHeap .pop (); const min = this .minHeap [0 ]; this .minHeap [0 ] = this .minHeap .pop (); this .heapifyDown (); return min; }; MinHeap .prototype .top = function ( ) { return this .minHeap .length > 0 ? this .minHeap [0 ] : null ; }; var obj = new MinHeap ();obj.push (-2 ); obj.push (0 ); obj.push (-3 ); console .log (obj.top ());console .log (obj.minHeap );