295. Find Median from Data Stream

LeetCode Link

class MedianFinder {
    private PriorityQueue smallMaxHeap = null;
    private PriorityQueue bigMinHeap = null;
    
    public MedianFinder() {
        smallMaxHeap = new PriorityQueue(10, Collections.reverseOrder());
        bigMinHeap = new PriorityQueue(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();
    }
}

你可能感兴趣的:(295. Find Median from Data Stream)