| 1 | // top K |
| 2 | // 长度是K的堆 |
| 3 | class Heap{ |
| 4 | constructor(compare){ |
| 5 | this.arr = [0] //忽略0这个索引 |
| 6 | this.compare = compare?compare:(a,b)=>a>b |
| 7 | } |
| 8 | get size(){ |
| 9 | return this.arr.length-1 |
| 10 | } |
| 11 | push(item){ |
| 12 | // 新增元素 |
| 13 | this.arr.push(item) |
| 14 | this.shiftUp(this.arr.length-1) |
| 15 | } |
| 16 | shiftUp(k){ |
| 17 | let {arr,compare,parent} = this |
| 18 | while(k>1 && compare(arr[k],arr[parent(k)])){ |
| 19 | this.swap(parent(k),k) |
| 20 | k = parent(k) |
| 21 | } |
| 22 | } |
| 23 | pop(){ |
| 24 | // 弹出堆顶 |
| 25 | if(this.arr.length==1) return null |
| 26 | this.swap(1, this.arr.length-1) |
| 27 | let head = this.arr.pop() //删除堆顶 |
| 28 | this.sinkDown(1) |
| 29 | return head |
| 30 | } |
| 31 | sinkDown(k){ |
| 32 | let {arr,compare,left,right,size} = this |
| 33 | while(left(k)<=size){ |
| 34 | let child = left(k) |
| 35 | if(right(k)<=size && compare(arr[right(k)],arr[child])){ |
| 36 | child = right(k) |
| 37 | } |
| 38 | if(compare(arr[k],arr[child])) { |
| 39 | return |
| 40 | } |
| 41 | this.swap(k,child) |
| 42 | k = child //继续向下 |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | peek(){ |
| 47 | // 获取堆顶元素 |
| 48 | return this.arr[1] |
| 49 | } |
| 50 | left(k){ |
| 51 | return k*2 |
| 52 | } |
| 53 | right(k){ |
| 54 | return k*2+1 |
| 55 | } |
| 56 | parent(k){ |
| 57 | return Math.floor(k/2) |
| 58 | } |
| 59 | swap(i,j){ |
| 60 | [this.arr[i],this.arr[j]] = [this.arr[j],this.arr[i]] |
nothing calls this directly
no outgoing calls
no test coverage detected