295. Find Median from Data Strea

2018-05-02  本文已影响0人  Super_Alan

LeetCode Link

class MedianFinder {
    private PriorityQueue<Integer> smallMaxHeap = null;
    private PriorityQueue<Integer> bigMinHeap = null;
    
    public MedianFinder() {
        smallMaxHeap = new PriorityQueue<Integer>(10, Collections.reverseOrder());
        bigMinHeap = new PriorityQueue<Integer>(10);
    }
    
    // keep smallMaxHeap.size euqal to (bigMinHeap.size or bigMinHeap.size + 1) 
    public void addNum(int num) {
        if (smallMaxHeap.isEmpty() || num < smallMaxHeap.peek()) {
            smallMaxHeap.offer(num);
            if (smallMaxHeap.size() == bigMinHeap.size() + 2) {
                bigMinHeap.offer(smallMaxHeap.poll());
            }
        } else {
            bigMinHeap.offer(num);
            if (bigMinHeap.size() > smallMaxHeap.size()) {
                smallMaxHeap.offer(bigMinHeap.poll());
            }
        }
    }
    
    public double findMedian() {
        if (smallMaxHeap.isEmpty()) {
            return 0.0;
        } else if (smallMaxHeap.size() == bigMinHeap.size()) {
            return (smallMaxHeap.peek() + bigMinHeap.peek()) / 2.0;
        }
        
        return (double)smallMaxHeap.peek();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读