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.
staticdouble[]runningMedian(int[]a){/* * Write your code here. */intn=a.length;PriorityQueue<Integer>highel=newPriorityQueue<Integer>();PriorityQueue<Integer>lowel=newPriorityQueue<Integer>(n/2,Collections.reverseOrder());doubleans[]=newdouble[n];if(n==0)returnans;if(n==1){ans[0]=a[0];returnans;}ans[0]=a[0];ans[1]=(a[0]+a[1])/2.0;intmin=(int)Math.min(a[0],a[1]);intmax=(int)Math.max(a[0],a[1]);lowel.add(min);highel.add(max);inti;for(i=2;i<a.length;i++){intele=a[i];intprevMedian=highel.peek();if(ele>prevMedian)highel.add(ele);// add to minHeapelselowel.add(ele);// add to maxHeapintlsize=lowel.size();intrsize=highel.size();if(lsize>=rsize+2){intp=lowel.poll();//lowel.remove(p);highel.add(p);}elseif(rsize>=lsize+2){intp=highel.poll();//highel.remove(p);lowel.add(p);}if(lowel.size()==highel.size()){ans[i]=(lowel.peek()+highel.peek())/2.0;}elseif(lowel.size()>highel.size()){ans[i]=lowel.peek();}elseans[i]=highel.peek();}returnans;}
Can't figurev out why this fails after the first test case? Seems to work for all the test cases I can think of,
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Find the Running Median
You are viewing a single comment's thread. Return to all comments →
Can't figurev out why this fails after the first test case? Seems to work for all the test cases I can think of,