cherrychenlee

导航

 

原文地址:https://www.jianshu.com/p/7d7ef2a018b2

时间限制:1秒 空间限制:32768K

题目描述

如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。

我的代码

class Solution {
    priority_queue<int,vector<int>,greater<int>> minHeap;
    priority_queue<int,vector<int>,less<int>> maxHeap;
public:
    void Insert(int num)
    {
        if(maxHeap.empty() || num<maxHeap.top())
            maxHeap.push(num);
        else
            minHeap.push(num);
        if(maxHeap.size()==minHeap.size()+2){
            minHeap.push(maxHeap.top());
            maxHeap.pop();
        }
        if(maxHeap.size()+1==minHeap.size()){
            maxHeap.push(minHeap.top());
            minHeap.pop();
        }
    }

    double GetMedian()
    { 
        if(maxHeap.size()==minHeap.size()+1)
            return maxHeap.top();
        else
            return (maxHeap.top()+minHeap.top())/2.0;
    }
};

运行时间:3ms
占用内存:476k

posted on 2019-05-07 13:22  cherrychenlee  阅读(70)  评论(0编辑  收藏  举报