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.
Easy C++ Solution using Heaps in O(nlog(n)) Time Complexity.
vector<double>runningMedian(vector<int>&a){priority_queue<int>maxHeap;// smaller halfpriority_queue<int,vector<int>,greater<int>>minHeap;// larger halfvector<double>ans;for(intnum:a){maxHeap.push(num);// Move largest of smaller half to min heapinttemp=maxHeap.top();maxHeap.pop();minHeap.push(temp);// Balance heaps sizesif(minHeap.size()>maxHeap.size()){temp=minHeap.top();minHeap.pop();maxHeap.push(temp);}// Calculate mediandoublemedian;if(maxHeap.size()!=minHeap.size()){median=maxHeap.top();}else{median=(maxHeap.top()+minHeap.top())/2.0;}// Round to 1 decimal placemedian=round(median*10.0)/10.0;ans.push_back(median);}returnans;}
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 →
Easy C++ Solution using Heaps in O(nlog(n)) Time Complexity.