Thursday, 20 October 2016

Find the Running Median (CTCI)

Problem: Find the Running Median
Given an input stream of  integers, find the running median after each input.

priority_queue<int> leftHalf;
priority_queue<int, vector<int>, greater<int> > rightHalf;

void insert(int pos, int val)
{
    if(pos & 1)
    {
        rightHalf.push(val);
        val = rightHalf.top();
        rightHalf.pop();
        leftHalf.push(val);
    }
    else 
    {
        rightHalf.push(val);
        if(leftHalf.top()>rightHalf.top())
        {
              int leftMax = leftHalf.top();
                leftHalf.pop();
              int rightMin = rightHalf.top();
                rightHalf.pop();
              leftHalf.push(rightMin);
              rightHalf.push(leftMax);
        }
    }
   return;
}
        
double median(int pos)
{
    if(pos & 1)
        return (double) leftHalf.top();
    int ret = leftHalf.top()+rightHalf.top();
    return (double) ret / 2.0;
}

int main(){
    int n;
    cin >> n;
    vector<int> a(n+1);
    for(int a_i = 1;a_i <= n;a_i++){
       cin >> a[a_i];
       insert(a_i, a[a_i]);
       cout<< fixed << setprecision(1) << median(a_i) <<endl;
    }
    return 0;
}

No comments:

Post a Comment