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();
     */
  • 相关阅读:
    springboot+thymeleaf+pageHelper带条件分页查询
    用JavaScript写一个简单的计算器
    运用java反射机制获取实体方法报错,java.lang.NoSuchMethodException: int.<init>(java.lang.String)
    前端页面优化
    MySQL常用dos命令
    python 学习笔记(四) 统计序列中元素出现的频度(即次数)
    python 学习笔记(二):为元组的每个元素命名,提高程序的可读性
    python 学习笔记(一):在列表、字典、集合中根据条件筛选数据
    Python 字符串前面加u,r,b,f的含义
    python3中文件操作及编码
  • 原文地址:https://www.cnblogs.com/fatttcat/p/9998898.html
Copyright © 2011-2022 走看看