欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

查找数据里的中位数

程序员文章站 2022-06-17 19:54:54
...

使用两个堆,算法思路如下图所示。
查找数据里的中位数

class MedianFinder {
public:
    /** initialize your data structure here. */
    priority_queue<double> maxPQ;
    priority_queue<double, vector<double>, greater<double> > minPQ;
    MedianFinder() {

    }
    
    void addNum(int num) {
        if (maxPQ.empty()) {
            maxPQ.push(num);
            return;
        }
        if (maxPQ.size() == minPQ.size()) {
            if (num < maxPQ.top())
                maxPQ.push(num);
            else
                minPQ.push(num);
        }
        else if (maxPQ.size() == minPQ.size() + 1) {
            if (num < maxPQ.top()) {
                minPQ.push(maxPQ.top());
                maxPQ.pop();
                maxPQ.push(num);
            }
            else
                minPQ.push(num);
        }
        else if (maxPQ.size() + 1 == minPQ.size()) {
            if (num < minPQ.top())
                maxPQ.push(num);
            else {
                maxPQ.push(minPQ.top());
                minPQ.pop();
                minPQ.push(num);
            }
        }
    }
    
    double findMedian() {
        if (maxPQ.size() == minPQ.size())
            return (maxPQ.top() + minPQ.top()) / 2;
        else if (maxPQ.size() > minPQ.size())
            return maxPQ.top();
        else
            return minPQ.top();
    }
};

/**
 * Your MedianFinder object will be instantiated and called as such:
 * MedianFinder* obj = new MedianFinder();
 * obj->addNum(num);
 * double param_2 = obj->findMedian();
 */