295. Find Median from Data Stream

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();
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容