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();
     */
  • 相关阅读:
    艰苦创业,无怨无悔,他靠养蜂开拓创业路!
    农民工如何拥有500多家加盟连锁店,看他是怎样做到的?
    从小面馆到餐饮王国,他的成功靠的是什么?
    夫妻合体创业,两月收入15万,他们是怎样做到的?
    农民王永宝,打造了一片乡村旅游乐土
    10年时间,从摆地摊到开连锁店,他们夫妻二人如何度过?
    F5 服务说明
    python 获取pool 成员状态
    CloudCC CRM探讨:精细流程管理与员工悟性培养
    CloudCC CRM探讨:精细流程管理与员工悟性培养
  • 原文地址:https://www.cnblogs.com/fatttcat/p/9998898.html
Copyright © 2011-2022 走看看