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.
Getting timeout and one wrong answer with this:
Any suggestions?
#include<bits/stdc++.h>usingnamespacestd;voidmaxHeapify(vector<int>&arr,intiBegin){intiLeft=2*iBegin+1;intiRight=iLeft+1;intiLargest=iBegin;if(iLeft<arr.size()&&arr[iLeft]>arr[iLargest])iLargest=iLeft;if(iRight<arr.size()&&arr[iRight]>arr[iLargest])iLargest=iRight;if(iLargest!=iBegin){swap(arr[iLargest],arr[iBegin]);maxHeapify(arr,iLargest);}}voidminHeapify(vector<int>&arr,intiBegin){intiLeft=2*iBegin+1;intiRight=iLeft+1;intiSmallest=iBegin;if(iLeft<arr.size()&&arr[iLeft]<arr[iSmallest])iSmallest=iLeft;if(iRight<arr.size()&&arr[iRight]<arr[iSmallest])iSmallest=iRight;if(iSmallest!=iBegin){swap(arr[iSmallest],arr[iBegin]);minHeapify(arr,iSmallest);}}voidbuildMinHeap(vector<int>&arr){for(inti=arr.size()/2-1;i>=0;i--)minHeapify(arr,i);}voidbuildMaxHeap(vector<int>&arr){for(inti=arr.size()/2-1;i>=0;i--)maxHeapify(arr,i);}voidfindRunningMedian(vector<int>arr){//median even = (maxHeap[0] + minHeap[0] ) / 2//median odd = maxHeap[0]inti=0;vector<int>minHeap;vector<int>maxHeap;minHeap.reserve(arr.size()/2);maxHeap.reserve(arr.size()/2);cout<<fixed;cout<<setprecision(1);while(i<arr.size()){doublemedian=0.0;// add odd element to maxHeap, to keep it always >= minHeapif(i%2==0){// add to minHeap if greater than its min elementif(minHeap.size()&&minHeap[0]<arr[i]){//add to minHeapminHeap.push_back(arr[i]);// move the min element to maxHeap to maintain sizemaxHeap.push_back(minHeap[0]);minHeap.erase(minHeap.begin());buildMaxHeap(maxHeap);buildMinHeap(minHeap);}else{maxHeap.push_back(arr[i]);buildMaxHeap(maxHeap);}median=maxHeap[0];}else{// add to maxHeap if less than minHeap[0]if(minHeap.size()&&minHeap[0]>arr[i]){//add to minHeapmaxHeap.push_back(arr[i]);// move the max element to minHeap, to maintain sizeminHeap.push_back(maxHeap[0]);maxHeap.erase(maxHeap.begin());buildMaxHeap(maxHeap);buildMinHeap(minHeap);}else{minHeap.push_back(arr[i]);// special case to handle 2 element arrayif(i==1&&minHeap[0]<maxHeap[0]){swap(minHeap[0],maxHeap[0]);}buildMinHeap(minHeap);}median=((double)maxHeap[0]+(double)minHeap[0])/2;}cout<<median<<endl;i++;}}intmain(){intn;cin>>n;cin.ignore(numeric_limits<streamsize>::max(),'\n');vector<int>a(n);for(inti=0;i<n;i++){inta_item;cin>>a_item;cin.ignore(numeric_limits<streamsize>::max(),'\n');a[i]=a_item;}findRunningMedian(a);return0;}
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 →
Getting timeout and one wrong answer with this: Any suggestions?