其他分享
首页 > 其他分享> > 牛客OJ:两个堆完成数据流中位数的查询

牛客OJ:两个堆完成数据流中位数的查询

作者:互联网

#include <bits/stdc++.h>
using namespace std;

priority_queue<int> qmax;  // 多放一个
priority_queue<int, vector<int>, greater<int> > qmin;

void Insert(int num)
{
    if(qmax.empty()){
        qmax.push(num);
        return ;
    }
    int a = qmax.top();
    if(qmin.empty()){
        if(num < a){
            qmax.pop();
            qmax.push(num);
            qmin.push(a);
        }else{
            qmin.push(num);
        }
        return;
    }
    int b = qmin.top();
    if(num >= a && num <= b){
        if((qmax.size() + qmin.size()) & 1){
            qmin.push(num);
        }else{
            qmax.push(num);
        }
        return ;
    }
    if(num < a){
        if((qmax.size() + qmin.size()) & 1){
            qmax.pop();
            qmax.push(num);
            qmin.push(a);
        }else{
            qmax.push(num);
        }
        return ;
    }
    if((qmax.size() + qmin.size()) & 1){
        qmin.push(num);
    }else{
        qmin.pop();
        qmin.push(num);
        qmax.push(b);
    }
}

double GetMedian()
{
    int a = qmax.size();
    int b = qmin.size();
    if(a <= 0) return 0;
    if(b <= 0) return qmax.top();
    if( (a+b)&1 ){
        return qmax.top();
    }else{
        return (qmax.top() + qmin.top()) * 0.5;
    }
}

int main(){
    int a[] = {5,2,3,4,1,6,7,0,8};
    for(int i=0;i<9;i++){
        Insert(a[i]);
        cout<<GetMedian()<<endl;
    }
    return 0;
}

标签:num,OJ,int,qmax,中位数,牛客,qmin,push,return
来源: https://blog.csdn.net/ShellDawn/article/details/88949187