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();
     */
  • 相关阅读:
    go标准库的学习-net/http
    go标准库的学习-sync互斥
    sqlplus命令大全
    Oracle 11g安装步骤详谈
    安装64位版Oracle11gR2后无法启动SQLDeveloper的解决方案(原创) (2016-10-29 下午01:56)
    Dos命令查看端口占用及关闭进程
    access denied ("java.net.SocketPermission" "localhost:1527" "listen,resolve")
    Hibernate的集合映射与sort、order-by属性
    Hibernate总结2 API和配置文件
    MyEclipse8.5启动无法选择工作空间的问题
  • 原文地址:https://www.cnblogs.com/fatttcat/p/9998898.html
Copyright © 2011-2022 走看看