Compute the running median of a sequence of numbers. That is, given a stream of numbers, print out the median of the list so far on each new element.
Recall that the median of an even-numbered list is the average of the two middle numbers.
For example, given the sequence [2, 1, 5, 7, 2, 0, 5], your algorithm should print out:
Example:
Input: arr = [2,1,5,7,2,0,5]
Output: [2, 1.5, 2, 3.5, 2, 2, 2]
Approach
C++
#include <bits/stdc++.h>using namespace std;//maximum priority queuepriority_queue<double> max1;//minimum priority queuepriority_queue<double, vector<double>, greater<double>> min1;//variable to hold the mediandouble median = 0;//add numner into the priority//queuesvoid addNum(int num){//if both are of equal sizeif (max1.size() == min1.size()){//if current element is//greter than median then//push into minimum priority//queue and set meadin as top//of min priority queueif (num > median){min1.push(num);median = min1.top();}//else push into the max queue//and set median as top of max queueelse{max1.push(num);median = max1.top();}}//if min size is moreelse if (min1.size() > max1.size()){//if element is more than median//then push the top of min into max//and current element into the minif (num > median){max1.push(min1.top());min1.pop();min1.push(num);}//else push into the maxelsemax1.push(num);//set median as average of//min top and max top elementsmedian = (min1.top() + max1.top()) / 2;}//if max size if greaterelse{//if current is more than then//median then push into the min//queueif (num > median){min1.push(num);}//else push the top of max into//the min and current into the maxelse{min1.push(max1.top());max1.pop();max1.push(num);}//set the median as average of//top of min and maxmedian = (min1.top() + max1.top()) / 2;}}//function to find the meadin of running//streamdouble findMedian(){return median;}int main(){int arr[] = {2, 1, 5, 7, 2, 0, 5};int n = sizeof(arr) / sizeof(arr[0]);cout << "[";for (int i = 0; i < n; i++){addNum(arr[i]);cout << findMedian();if (i != n - 1)cout << ", ";}cout << "]";return 0;}
No comments:
Post a Comment