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();
     */
  • 相关阅读:
    bzoj 2038 [2009国家集训队]小Z的袜子(hose)
    搭配飞行员
    codevs 1022 覆盖
    Tyvj-1338 QQ农场
    bzoj 3894 文理分科
    bzoj 1877 [SDOI2009]晨跑
    poj 3304 判断是否存在一条直线与所有线段相交
    poj 2318 向量的叉积二分查找
    poj 3608 凸包间的最小距离
    LA 4728 旋转卡壳算法求凸包的最大直径
  • 原文地址:https://www.cnblogs.com/fatttcat/p/9998898.html
Copyright © 2011-2022 走看看