力扣295:数据流的中位数

 力扣(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 left = new PriorityQueue<>(
        (a,b) -> Integer.compare(b,a)
    );
    //小顶堆
    private PriorityQueue 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();
 */

你可能感兴趣的:(java,前端,javascript)