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

  • 相关阅读:
    NABC的特点分析
    梦断代码读后感(三)
    大道至简-“(我) 能不能学会写程序”
    课堂练习-找水王续
    找1
    课堂练习-找水王
    课堂练习-电梯调度
    课堂练习——计算法能够计算出读者购买一批书的最低价格。
    团队项目—二手书店特色
    梦断代码阅读笔记三
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5081437.html
Copyright © 2011-2022 走看看