力扣295:数据流的中位数

发布时间:2024年01月23日

?力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

?优先级队列,大小顶堆

class MedianFinder {

    public MedianFinder() {

    }
    
    public void addNum(int num) {
        if(left.size() == right.size()){
            right.offer(num);
            left.offer(right.poll());
        }else{
            left.offer(num);
            right.offer(left.poll());
        }
    }
    
    public double findMedian() {
        if(left.size() == right.size()){
            return (left.peek() + right.peek()) /2.0;
        }else{
            return left.peek();
        }
    }
    //大顶堆
    private PriorityQueue<Integer> left = new PriorityQueue<>(
        (a,b) -> Integer.compare(b,a)
    );
    //小顶堆
    private PriorityQueue<Integer> right = new PriorityQueue<>();
}

/**
 * Your MedianFinder object will be instantiated and called as such:
 * MedianFinder obj = new MedianFinder();
 * obj.addNum(num);
 * double param_2 = obj.findMedian();
 */

文章来源:https://blog.csdn.net/2301_81408943/article/details/135757246
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。