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();
     */
  • 相关阅读:
    构建之法十五
    十二周学习总结笔记
    构建之法十四
    构建之法十一
    构建之法十三
    用户体验评价
    构建之法第十章
    十一周总结学习笔记
    找水王
    十周总结学习笔记
  • 原文地址:https://www.cnblogs.com/immjc/p/9466784.html
Copyright © 2011-2022 走看看