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.
Ruby solution with custom Binary Heap implementation (as there is no built-in Heap in Ruby's core lib)
classAbstractBinHeapdefinitialize@store=[]enddefempty?@store.empty?enddefsize@store.sizeendaliaslengthsizedefto_stmp=duporder=[]order<<tmp.popuntiltmp.empty?order.join(' ')endaliasinspectto_sdefadd(e)@store<<eheapify_up(@store.size-1)endalias<<adddefpeekifempty?nilelse@store[0]endendaliasnextpeekdefpopreturnnilifempty?e=@store[0]@store[0]=@store[-1]@store.popheapify_down(0)eend# Delete first occurence of e.defdelete(e)pos=@store.index(e)ifpos.nil?nilelsedelete_at(pos)endendprotectedattr_writer:storedefdupcl=self.class.newcl.store=@store.dupclendprivatedefdelete_at(pos)returnnilifpos>=@store.lengthe=@store[pos]@store[pos]=most_sig_valheapify_up(pos)popeenddefparent(pos)(pos-1)/2enddeflchild(pos)pos*2+1enddefrchild(pos)pos*2+2enddefheapify_up(pos)returnifpos==0||pos>=@store.lengthloopdoparent=(pos-1)/2breakunlesspos>0&&compare(@store[pos],@store[parent])@store[pos],@store[parent]=@store[parent],@store[pos]pos=parentendenddefheapify_down(pos)returnifpos>=@store.lengthwhilelchild(pos)<@store.lengthlchild=lchild(pos)rchild=rchild(pos)minchild=ifrchild<@store.lengthcompare(@store[lchild],@store[rchild])?lchild:rchildelselchildendifcompare(@store[minchild],@store[pos])@store[pos],@store[minchild]=@store[minchild],@store[pos]pos=minchildelsebreakendendendendclassMinHeap<AbstractBinHeapprivatedefcompare(obj1,obj2)obj1<obj2enddefmost_sig_val-1*Float::INFINITYendendclassMaxHeap<AbstractBinHeapprivatedefcompare(obj1,obj2)obj1>obj2enddefmost_sig_valFloat::INFINITYendenddefrunning_median(arr)smaller=MaxHeap.newlarger=MinHeap.newarr.mapdo|e|ifsmaller.empty?||e<=smaller.peeksmaller<<eelselarger<<eendifsmaller.size<larger.sizesmaller<<larger.popelsifsmaller.size-1>larger.sizelarger<<smaller.popendiflarger.empty?smaller.peekelsesmaller.size==larger.size?(smaller.peek+larger.peek)/2:smaller.peekendendendn=gets.to_iarr=Array.new(n)n.times{|i|arr[i]=gets.to_f}puts(running_median(arr).map{|m|format('%.1f',m)})
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 →
Ruby solution with custom Binary Heap implementation (as there is no built-in Heap in Ruby's core lib)