zoukankan      html  css  js  c++  java
  • Leetcode: 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.
    
    Examples: 
    [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.
    For example:
    
    add(1)
    add(2)
    findMedian() -> 1.5
    add(3) 
    findMedian() -> 2

    最大最小堆

    复杂度

    时间 O(logN) insert, O(1) query, 空间 O(N)

    思路

    维护一个最大堆,一个最小堆。最大堆存的是到目前为止较小的那一半数,最小堆存的是到目前为止较大的那一半数,这样中位数只有可能是堆顶或者堆顶两个数的均值。而维护两个堆的技巧在于判断堆顶数和新来的数的大小关系,还有两个堆的大小关系。我们始终维护MaxHeap>=MinHeap

    With the help of java 8, you can simply write this (no initial capacity needed any more) :

    PriorityQueue<Integer> max = new PriorityQueue(Collections.reverseOrder());
     1 class MedianFinder {
     2     // max queue is always larger or equal to min queue
     3     PriorityQueue<Integer> min = new PriorityQueue();
     4     PriorityQueue<Integer> max = new PriorityQueue(1000, Collections.reverseOrder()); // see above
     5     // Adds a number into the data structure.
     6     public void addNum(int num) {
     7         max.offer(num);
     8         min.offer(max.poll());
     9         if (max.size() < min.size()){
    10             max.offer(min.poll());
    11         }
    12     }
    13 
    14     // Returns the median of current data stream
    15     public double findMedian() {
    16         if (max.size() == min.size()) return (max.peek() + min.peek()) /  2.0;
    17         else return max.peek();
    18     }
    19 };

    当然其它比较笨的办法可以binary search插入arraylist,保持有序性

  • 相关阅读:
    How to install php 7.x on CentOS 7
    Azure新建的CentOS设置root账户的密码
    远程激活.NET REFLECTOR(不能断网)
    C# WebApi 配置复杂路由不生效的问题
    在Mac上激活Adobe产品
    WIN10更新后出现无法联网的问题
    Mac安装SSHFS挂载远程服务器上的文件夹到本地
    输入三个数值,输出其中的最大值和最小值
    登录接口,只为自己能尽快吐槽一下这段代码
    随手记
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5081437.html
Copyright © 2011-2022 走看看