We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
classHeap{constructor(){this.heap=[];this.pushCount=Number.MIN_SAFE_INTEGER;}percUp(index){letp;while(index>0&&smaller(this.heap[index],this.heap[p=parent(index)])){lett=this.heap[index];this.heap[index]=this.heap[p];this.heap[p]=t;index=p;}}percDown(index){letl;while((l=leftChi(index))<this.heap.length){if(l+1<this.heap.length&&smaller(this.heap[l+1],this.heap[l])){l=l+1;}if(smaller(this.heap[index],this.heap[l])){break;}lett=this.heap[index];this.heap[index]=this.heap[l];this.heap[l]=t;index=l;}}push(node){node.pushCount=++this.pushCount;this.heap.push(node);this.percUp(this.heap.length-1);}toArray(){returnthis.heap;}*[Symbol.iterator](){for(leti=0;i<this.heap.length;i++){yieldthis.heap[i].data;}}remove(value){letj=0;for(leti=0;i<this.heap.length;i++){if(value!==this.heap[i].priority){this.heap[j]=this.heap[i];j++;}}this.heap.splice(j);for(leti=parent(this.heap.length-1);i>=0;i--){this.percDown(i);}returnthis;}}functionleftChi(i){return(i<<1)+1;}functionparent(i){return(i+1>>1)-1;}functionsmaller(x,y){if(x.priority!==y.priority){returnx.priority<y.priority;}else{returnx.pushCount<y.pushCount;}}functionprocessData(input){//Enter your code hereconstheap=newHeap();constarr=input.split("\n");for(leti=0;i<arr.length;i++){constinnerArr=arr[i].split(" ");constquery=Number(innerArr[0]);if(query==1){constvalue=Number(innerArr[1]);heap.push({priority:value});}elseif(innerArr[0]==2){constvalue=Number(innerArr[1]);heap.push({priority:value});heap.remove(value)}elseif(innerArr[0]==3){console.log(heap.toArray()[0].priority);}}}
QHEAP1
You are viewing a single comment's thread. Return to all comments →