您好,欢迎访问代理记账网站
  • 价格透明
  • 信息保密
  • 进度掌控
  • 售后无忧

剑指 Offer 41. 数据流中的中位数

链接:剑指 Offer 41. 数据流中的中位数

题解:https://leetcode-cn.com/problems/shu-ju-liu-zhong-de-zhong-wei-shu-lcof/solution/mian-shi-ti-41-shu-ju-liu-zhong-de-zhong-wei-shu-y/

Picture1.png

class MedianFinder {
    // left
    priority_queue<int, vector<int>, less<int>> max_heap;
    // right
    priority_queue<int, vector<int>, greater<int>> min_heap;
    public:
        /** initialize your data structure here. */
        MedianFinder() {

        }

        void addNum(int num) {
            if (max_heap.size() != min_heap.size()) {
                max_heap.push(num);
                int top = max_heap.top();
                max_heap.pop();
                min_heap.push(top);
            } else {
                min_heap.push(num);
                int top = min_heap.top();
                min_heap.pop();
                max_heap.push(top);
            }
        }

        double findMedian() {
            if (max_heap.size() == min_heap.size()) {
                return (max_heap.top() + min_heap.top()) / 2;
            } else {
                return max_heap.top();
            }
        }
};
/**
 * Your MedianFinder object will be instantiated and called as such:
 * MedianFinder* obj = new MedianFinder();
 * obj->addNum(num);
 * double param_2 = obj->findMedian();
 */

 

 


分享:

低价透明

统一报价,无隐形消费

金牌服务

一对一专属顾问7*24小时金牌服务

信息保密

个人信息安全有保障

售后无忧

服务出问题客服经理全程跟进