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

原文地址:https://www.cnblogs.com/EdwardLiu/p/5081437.html