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.
Solution with my original Heap class and an optimized way faster one:
classHeap{// My original implementation - cagilsconstructor(comp){this.heap=[];if(comp==="max"||!comp)this.comp=(a,b)=>a>b;elseif(comp==="min")this.comp=(a,b)=>a<b;elsethis.comp=comp;}_heapify(){for(leti=parseInt(this.heap.length/2-1);i>=0;i--)Heap.heapify(this.heap,this.heap.length,i,this.comp);}staticheapify(arr,n,i,comp){letfirst=i;letli=2*i+1;letri=2*i+2;if(li<n&&comp(arr[li],arr[first]))first=li;if(ri<n&&comp(arr[ri],arr[first]))first=ri;if(first!==i){[arr[i],arr[first]]=[arr[first],arr[i]];Heap.heapify(arr,n,first,comp);}}push=(data)=>{this.heap.push(data);this._heapify();};remove(data){constsize=this.heap.length;leti=this.heap.findIndex((e)=>e===data);if(i===-1)i=size;[this.heap[i],this.heap[size-1]]=[this.heap[size-1],this.heap[i]];this.heap.splice(size-1);this._heapify();returndata;}peek=()=>this.heap[0];pop=()=>this.remove(this.heap[0]);size=()=>this.heap.length;getList=()=>this.heap;}class_Heap{// faster implementationconstructor(comp){this.a=[];if(comp==="min"||!comp)this.comp=(a,b)=>a<b;elseif(comp==="max")this.comp=(a,b)=>a>b;elsethis.comp=comp;}up(i){//const pi = (i - 1) >> 1;//Math.floor((i - 1) / 2)constpi=Math.floor((i-1)/2);if(this.comp(this.a[i],this.a[pi])){[this.a[pi],this.a[i]]=[this.a[i],this.a[pi]];this.up(pi);}}down(i){constlci=i*2+1;constrci=lci+1;constpi=i;consta_i=this.a[i];if(this.comp(this.a[lci],a_i)||this.comp(this.a[rci],a_i)){if(this.comp(this.a[lci],a_i)&&this.comp(this.a[rci],a_i))i=this.comp(this.a[lci],this.a[rci])?lci:rci;elsei=this.comp(this.a[lci],a_i)?lci:rci;this.a[pi]=this.a[i];this.a[i]=a_i;this.down(i);}}push(num){this.a.push(num);this.up(this.a.length-1);}pop(){constdeletedVal=this.a[0];this.a.length>1?this.a[0]=this.a.pop():this.a.pop();this.down(0);returndeletedVal;}peek(){returnthis.a[0]}size=()=>this.a.length;getList=()=>this.a;}functionrunningMedian(a){consthighers=new_Heap('min');constlowers=new_Heap('max');for(constnofa){if(lowers.size()===0||lowers.peek()>n)lowers.push(n);elsehighers.push(n);let[big,small]=highers.size()>lowers.size()?[highers,lowers]:[lowers,highers];letdiff=big.size()-small.size();if(big.size()-small.size()>1){small.push(big.pop());diff=0;}constout=diff===0?(big.peek()+small.peek())/2:big.peek();console.log(out.toFixed(1))}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Heaps: Find the Running Median
You are viewing a single comment's thread. Return to all comments →
Solution with my original Heap class and an optimized way faster one: