zoukankan      html  css  js  c++  java
  • [LeetCode] Find Median from Data Stream

     

    Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.

    For example,

    [2,3,4], the median is 3

    [2,3], the median is (2 + 3) / 2 = 2.5

    Design a data structure that supports the following two operations:

    • void addNum(int num) - Add a integer number from the data stream to the data structure.
    • double findMedian() - Return the median of all elements so far.

    Example:

    addNum(1)
    addNum(2)
    findMedian() -> 1.5
    addNum(3) 
    findMedian() -> 2

    找出数字流中的中位数。

    使用两个优先队列将流入的结果分成两部分,左部分为最大堆(存储中位数左侧的元素)。右部分是最小堆(存储中位数右侧的元素)。并维护一个插入元素的计数值。

    假定如果把元素放入到最小堆中,则需要把左侧最大堆中的最大值放入右侧最小堆中。所以要先把元素放入左侧最大堆中,然后把最大堆中的最大值放入右侧最小堆,才能保证右侧最小堆的最小值大于左侧最大堆的最大值。

    当压入偶数次时,中位数是最大堆数值与最小堆数值和的一半,当压入奇数次时,中位数是最小堆数值。

    参考代码如下:

    class MedianFinder {
    public:
        /** initialize your data structure here. */
        MedianFinder() {
            
        }
        
        void addNum(int num) {
            if (count % 2 == 0)
            {
                left.push(num);
                right.push(left.top());
                left.pop();
            }
            else
            {
                right.push(num);
                left.push(right.top());
                right.pop();
            }
            count++;
        }
        
        double findMedian() {
            if (count % 2 == 0)
            {
                return (left.top()+right.top())/2.0;
            }
            else
            {
                return right.top();
            }
        }
    private:
        priority_queue<int, vector<int>, less<int>> left;
        priority_queue<int, vector<int>, greater<int>> right;
        int count = 0;
    };
    
    /**
     * Your MedianFinder object will be instantiated and called as such:
     * MedianFinder obj = new MedianFinder();
     * obj.addNum(num);
     * double param_2 = obj.findMedian();
     */
  • 相关阅读:
    HTML网页背景图很长要有滚动条滑动
    CentOS 6.6下安装配置Tomcat环境
    centos安装jdk1.7.80的rpm包
    vmware12共享windows的文件给虚拟的linux
    Oracle jdk 历史版本官方下载地址及下载方法
    CentOS所有版本下载地址分享
    为什么说docker可以保护Nginx、Tomcat、Mysql呢?
    Linux下安装Nginx依赖包和Nginx的命令
    Nginx的启动、停止、重启
    nginx无法启动: libpcre.so.1/libpcre.so.0: cannot open shared object file解决办法
  • 原文地址:https://www.cnblogs.com/immjc/p/9466784.html
Copyright © 2011-2022 走看看