leetcodej剑指offer41.数据流中的中位数

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

例如,

[2,3,4] 的中位数是 3

[2,3] 的中位数是 (2 + 3) / 2 = 2.5

设计一个支持以下两种操作的数据结构:

void addNum(int num) - 从数据流中添加一个整数到数据结构中。
double findMedian() - 返回目前所有元素的中位数。

class MedianFinder {
public:
    /** initialize your data structure here. */
    priority_queue<int, vector<int>, less<int> >big; // store the lager nums
    priority_queue<int, vector<int>, greater<int> > small; // store the smalller nums
    int ans = 0;
    MedianFinder() {
    }
    
    void addNum(int num) {
        ans ++;
        if(small.size() == big.size()){
            if(small.size() == 0) small.push(num);
            else if(num >= big.top()) small.push(num);
            else big.push(num);
        }
        else if(small.size() > big.size()){
            if(num <= small.top()) big.push(num);
            else{
                big.push(small.top());
                small.pop(); small.push(num);
            }
        }else{
            if(num >= big.top()) small.push(num);
            else{
                small.push(big.top());
                big.pop(); big.push(num);
            }
        }
    }
    
    double findMedian() {
        if(ans & 1) {
            if(small.size() > big.size()) return small.top() * 1.0;
            else return big.top() * 1.0;
        }
        else return (big.top() * 1.0 + small.top() * 1.0) / 2;
    }
};

/**
 * Your MedianFinder object will be instantiated and called as such:
 * MedianFinder* obj = new MedianFinder();
 * obj->addNum(num);
 * double param_2 = obj->findMedian();
 */
原文地址:https://www.cnblogs.com/shinianhuanniyijuhaojiubujian/p/15498975.html