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,保持有序性

  • 相关阅读:
    Redis系列(三)-Redis replication 实现主从复制(读写分离)
    Redis系列(二)-Redis的RDB和AOF两种持久化机制
    Redis系列(一)-CentOS7下Redis单机安装+自启动
    vmware安装centos 7,没有ifconfig命令,无法访问网络
    本博客停更
    「杂文」昨日之纯真,明日之坚毅
    OkHttpClient跳过证书验证
    java 获取十个工作日之前或之后的日期(算当天)
    java pdfBox给PDF添加图片水印
    docker pull 提示timeout
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5081437.html
Copyright © 2011-2022 走看看