大根堆,小根堆

数据流中的中位数

http://www.nowcoder.com/questionTerminal/9be0172896bd43948f8a32fb954e1be1

数据流小于大根堆根节点则插入大根堆,否则插入小根堆,这样大根堆维护小的那一半,小根堆维护大的那一半.

class Solution {
public:
    void Insert(int num)
    {
        if (bigRootQueue.empty() || num <= bigRootQueue.top()) {
            bigRootQueue.push(num);
        } else {
            littleRootQueue.push(num);
        }
        if (bigRootQueue.size() > littleRootQueue.size() + 1) {
            littleRootQueue.push(bigRootQueue.top());
            bigRootQueue.pop();
        }
        if (littleRootQueue.size() > bigRootQueue.size()) {
            bigRootQueue.push(littleRootQueue.top());
            littleRootQueue.pop();
        }
    }

    double GetMedian()
    {
        int len = littleRootQueue.size() + bigRootQueue.size();
        if (len % 2) {
            return (double)bigRootQueue.top();
        } else {
            return (double)(bigRootQueue.top() + littleRootQueue.top()) / 2;
        }
    }

private:
    priority_queue<int, vector<int>, greater<int>> littleRootQueue;
    priority_queue<int, vector<int>, less<int>> bigRootQueue;
};
全部评论
bigRootQueue.empty() || num <= bigRootQueue.top() //为什么写成num <= bigRootQueue.top() ||bigRootQueue.empty() 会AC不过呢,说是您的程序发生段错误,可能是数组越界,堆栈溢出(比如,递归调用层数太多)等情况引起
点赞 回复
分享
发布于 2020-07-14 22:29

相关推荐

点赞 评论 收藏
转发
2 收藏 评论
分享
牛客网
牛客企业服务