[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

分析:维护一个大顶堆(maxHeap)和一个小顶堆(minHeap),其中大顶堆的元素都小于小顶堆的元素,比如add 2, 3, 4, 5, 6后,堆内的元素如下:

maxHeap
4
3
2
minHeap
5
6

当maxHeap.size() != minHeap.size()时,返回maxHeap.peek();当maxHeap.size() == minHeap.size()时,返回(maxHeap.peek() + minHeap.peek())/2.

Java代码如下:

    PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
    PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(new Comparator<Integer>() {
        public int compare(Integer o1, Integer o2) {
            return o2 - o1;
        };
    });
    // Adds a number into the data structure.
    public void addNum(int num) {
        maxHeap.offer(num);
        minHeap.offer(maxHeap.poll());
        if (maxHeap.size() < minHeap.size()) {
            maxHeap.offer(minHeap.poll());
        }
    }

    // Returns the median of current data stream
    public double findMedian() {
        return maxHeap.size() == minHeap.size() ? (double)(maxHeap.peek()+minHeap.peek())/2 : maxHeap.peek();
    }
原文地址:https://www.cnblogs.com/lasclocker/p/4928579.html