[leetcode] 295. Find Median from Data Stream

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33096883/article/details/78317005
class MedianFinder {
    priority_queue<int> lo;                              // max heap
    priority_queue<int, vector<int>, greater<int>> hi;   // min heap

public:
    // Adds a number into the data structure.
    void addNum(int num)
    {
        lo.push(num);                                    // Add to max heap

        hi.push(lo.top());                               // balancing step
        lo.pop();

        if (lo.size() < hi.size()) {                     // maintain size property
            lo.push(hi.top());
            hi.pop();
        }
    }

    // Returns the median of current data stream
    double findMedian()
    {
        return lo.size() > hi.size() ? (double) lo.top() : (lo.top() + hi.top()) * 0.5;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_33096883/article/details/78317005
今日推荐