数据流中的中位数(剑指offer)

数据流中的中位数

如何得到一个数据流中的中位数?

如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。

如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。

样例

输入:1, 2, 3, 4

输出:1,1.5,2,2.5

解释:每当数据流读入一个数据,就进行一次判断并输出当前的中位数。
class Solution {
public:
    int idx=0;
    priority_queue<int> b;
    priority_queue<int,vector<int>,greater<int>> a;
    void insert(int num){
        b.push(num);
        idx++;
        if(a.size()&&a.top()<b.top())
        {
            int m=a.top();
            int n=b.top();
            a.pop();
            b.pop();
            a.push(n);
            b.push(m);
        }
        if(b.size()>a.size()+1)
        {
            a.push(b.top());
            b.pop();
        }
    }

    double getMedian(){
        if(idx%2==0)
            return (a.top()+b.top())/2.0;
        else    return b.top();
    }
};
发布了48 篇原创文章 · 获赞 1 · 访问量 1798

猜你喜欢

转载自blog.csdn.net/zhongxinyun/article/details/104562727