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();
     */
  • 相关阅读:
    mysql 初始密码 设置
    jsp基础知识(基本的语法及原理)
    hdu 2473 Junk-Mail Filter (并查集之点的删除)
    java版本的学生管理系统
    java操作数据库出现(][SQLServer 2000 Driver for JDBC]Error establishing socket.)的问题所在即解决办法
    Java学习之约瑟夫环的两中处理方法
    hdu 3367(Pseudoforest ) (最大生成树)
    hdu 1561 The more, The Better (树上背包)
    Nginx + Lua 搭建网站WAF防火墙
    长连接和短连接
  • 原文地址:https://www.cnblogs.com/immjc/p/9466784.html
Copyright © 2011-2022 走看看