zoukankan      html  css  js  c++  java
  • 295. 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

    Follow up:

    1. If all integer numbers from the stream are between 0 and 100, how would you optimize it?
    2. If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it?

    用两个heap(min heap和max heap),较小的一半元素放进max heap,较大的一半元素放进min heap,两个heap的size之差不超1,最后的答案在两个堆顶元素中产生(min heap的最小值 -> 较大数里的最小值,max heap的最大值 -> 较小数里的最大值)。在平衡两个heap的大小时,如果大小之差=2了,把元素多的堆的堆顶元素弹出并加入到元素少的堆里。

    时间:O(logN) add element into heap + O(1) compute median -> O(NlogN),空间:O(N)

    class MedianFinder {
    
        /** initialize your data structure here. */
        PriorityQueue<Integer> minHeap;
        PriorityQueue<Integer> maxHeap;
        
        public MedianFinder() {
            minHeap = new PriorityQueue<>();
            maxHeap = new PriorityQueue<>((a, b) -> b - a);
        }
        
        public void addNum(int num) {
            if(maxHeap.isEmpty() || num <= maxHeap.peek())
                maxHeap.add(num);
            else
                minHeap.add(num);
            
            if(maxHeap.size() - minHeap.size() == 2)
                minHeap.add(maxHeap.poll());
            else if(minHeap.size() - maxHeap.size() == 2)
                maxHeap.add(minHeap.poll());
        }
        
        public double findMedian() {
            if(minHeap.size() > maxHeap.size())
                return (double)minHeap.peek();
            else if(maxHeap.size() > minHeap.size())
                return (double)maxHeap.peek();
            else
                return (double)(minHeap.peek() + maxHeap.peek()) / 2;
        }
    }
    
    /**
     * Your MedianFinder object will be instantiated and called as such:
     * MedianFinder obj = new MedianFinder();
     * obj.addNum(num);
     * double param_2 = obj.findMedian();
     */
  • 相关阅读:
    Beyond Compare工具栏操作按钮可以增加吗
    Beyond Compare同步压缩文件夹的步骤
    Beyond Compare和UltraCompare有什么不一样
    Beyond Compare表格比较该怎么控制行对齐
    Beyond Compare的这些使用技巧你喜欢吗
    设置Beyond Compare比较文件显示样式的方法
    图片比较有了它就可以了
    关于容斥做题随记
    Heron and His Triangle HDU
    No more tricks, Mr Nanguo HDU
  • 原文地址:https://www.cnblogs.com/fatttcat/p/9998898.html
Copyright © 2011-2022 走看看