MCPcopy Create free account
hub / github.com/course-dasheng/fe-algorithm / Heap

Class Heap

interview/502.ipo.js:16–75  ·  view source on GitHub ↗

* @param {number} k * @param {number} w * @param {number[]} profits * @param {number[]} capital * @return {number}

Source from the content-addressed store, hash-verified

14 */
15
16 class Heap{
17 constructor(compare){
18 this.arr = [0] //忽略0这个索引
19 this.compare = compare?compare:(a,b)=>a>b
20 }
21 get size(){
22 return this.arr.length-1
23 }
24 push(item){
25 // 新增元素
26 this.arr.push(item)
27 this.shiftUp(this.arr.length-1)
28 }
29 shiftUp(k){
30 let {arr,compare,parent} = this
31 while(k>1 && compare(arr[k],arr[parent(k)])){
32 this.swap(parent(k),k)
33 k = parent(k)
34 }
35 }
36 pop(){
37 // 弹出堆顶
38 if(this.arr.length==1) return null
39 this.swap(1, this.arr.length-1)
40 let head = this.arr.pop() //删除堆顶
41 this.sinkDown(1)
42 return head
43 }
44 sinkDown(k){
45 let {arr,compare,left,right,size} = this
46 while(left(k)<=size){
47 let child = left(k)
48 if(right(k)<=size && compare(arr[right(k)],arr[child])){
49 child = right(k)
50 }
51 if(compare(arr[k],arr[child])) {
52 return
53 }
54 this.swap(k,child)
55 k = child //继续向下
56 }
57 }
58
59 peek(){
60 // 获取堆顶元素
61 return this.arr[1]
62 }
63 left(k){
64 return k*2
65 }
66 right(k){
67 return k*2+1
68 }
69 parent(k){
70 return Math.floor(k/2)
71 }
72 swap(i,j){
73 [this.arr[i],this.arr[j]] = [this.arr[j],this.arr[i]]

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected