题目
相同题目:剑指:数据流中的中位数
优先队列介绍:https://blog.csdn.net/weixin_73616913/article/details/131361059
法1:优先队列
必须掌握的算法!!!
class MedianFinder {
PriorityQueue<Integer> queueBig;
PriorityQueue<Integer> queueSmall;
public MedianFinder() {
queueBig = new PriorityQueue<>((a, b) -> b.compareTo(a));
queueSmall = new PriorityQueue<>();
}
public void addNum(int num) {
if (queueBig.size() == queueSmall.size()) {
queueSmall.offer(num);
queueBig.offer(queueSmall.poll());
} else {
queueBig.offer(num);
queueSmall.offer(queueBig.poll());
}
}
public double findMedian() {
if (queueBig.size() != queueSmall.size()) {
return queueBig.peek();
} else {
return ((double) (queueBig.peek() + queueSmall.peek())) / 2.0;
}
}
}