数据流中的中位数

数据流中的中位数

题目描述

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

学习了STL的push_heap和pop_heap操作, 传送门

class Solution {
public:
    void Insert(int num)
    {
        if (((min.size() + max.size()) & 1) == 0) {    // 偶数, 应该插入最小堆中
            if (max.size() > 0 && max[0] > num) {    // 最大堆中的数字大于要插入的数字
                max.push_back(num);
                push_heap(max.begin(), max.end(), less<int>());
                
                num = max[0];
                
                pop_heap(max.begin(), max.end(), less<int>());
                max.pop_back();
            }
            min.push_back(num);
            push_heap(min.begin(), min.end(), greater<int>());
        }
        else {        // 奇数, 插入最大堆
            if (min.size() > 0 && min[0] < num) {   // 最小堆小于这个数
                min.push_back(num);
                push_heap(min.begin(), min.end(), greater<int>());
                
                num = min[0];
                
                pop_heap(min.begin(), min.end(), greater<int>());
                min.pop_back();
            }
            max.push_back(num);
            push_heap(max.begin(), max.end(), less<int>());
        }
    }

    double GetMedian()
    { 
        int size = min.size() + max.size();
        
        if (0 == size)
            return 0;
        
        if ((size & 1) == 1)
            return min[0];
        else 
            return (min[0] + max[0]) / 2.0;
    }
    
private:
    vector<int> min;
    vector<int> max;
};

优先级队列也遇到了

class Solution {
    priority_queue<int, vector<int>, less<int> > p;
    priority_queue<int, vector<int>, greater<int> > q;
     
public:
    void Insert(int num){
        if(p.empty() || num <= p.top()) p.push(num);
        else q.push(num);
        if(p.size() == q.size() + 2) q.push(p.top()), p.pop();
        if(p.size() + 1 == q.size()) p.push(q.top()), q.pop();
    }
    double GetMedian(){ 
      return p.size() == q.size() ? (p.top() + q.top()) / 2.0 : p.top();
    }
};
posted @ 2019-03-20 13:11  张飘扬  阅读(200)  评论(0编辑  收藏  举报