Find Median from Data Stream(Hard) ---Heap

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)

需要满足下面的约束条件:

  • 大顶堆中存储的元素 均不大于 小顶堆中的元素
  • MaxHeap.size() == MinHeap.size(),或者 MaxHeap.size() == MinHeap.size() + 1

Java代码:

public class MedianFinder {
    private PriorityQueue<Integer> minHeap;
    private PriorityQueue<Integer> maxHeap;

    public MedianFinder() {
        minHeap = new PriorityQueue<Integer>();
        maxHeap = new PriorityQueue<Integer>(Collections.reverseOrder());
    }

    public void addNum(int num){
        if((maxHeap.size() == 0) || maxHeap.peek() >= num) {
            maxHeap.offer(num);
            if(maxHeap.size() -1 > minHeap.size()) {
                minHeap.offer(maxHeap.poll());
            }
        } else if((minHeap.size() == 0) || minHeap.peek() < num) {
            minHeap.offer(num);
            if(minHeap.size() > maxHeap.size()) {
                maxHeap.offer(minHeap.poll());
            }
        } else {
            if(maxHeap.size() <= minHeap.size()) {
                maxHeap.offer(num);
            } else {
                minHeap.offer(num);
            }
        }
    }

    public double findMedian() {
        if(maxHeap.size() == minHeap.size()) {
            return (double)(maxHeap.peek() + minHeap.peek()) / 2.0;
        }
        else {
            return (double)maxHeap.peek();
        }
    }
}

results matching ""

    No results matching ""