力扣-295.数据流的中位数

题目链接

295.数据流的中位数

java 复制代码
class MedianFinder {
    PriorityQueue<Integer> left;//队头最大
    PriorityQueue<Integer> right;//队头最小

    public MedianFinder() {
        left = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        });
        right = new PriorityQueue<>();
    }

    public void addNum(int num) {
        if (left.size() <= right.size()) {
            left.offer(num);
        } else {
            right.offer(num);
        }
        if (!left.isEmpty() && !right.isEmpty() && left.peek() > right.peek()) {
            left.offer(right.poll());
            right.offer(left.poll());
        }
    }

    public double findMedian() {
        if (left.size() > right.size()) {
            return left.peek();
        } else {
            return (left.peek() + right.peek()) / 2.0;
        }
    }
}

小结:两个优先级队列,左队列最大值不超过右队列最小值,且左队列容量=右队列(偶数)或左队列容量=右队列+1(奇数),这样就可以根据两个队列的队头元素直接计算出中位数。