【优先队列】LeetCode 295. 数据流的中位数
题目链接
思路
维护两个优先队列,分别装载排序后数据流左边的数和数据流右边的数,其中 left
为大顶堆,right
为小顶堆。如果元素个数是奇数,则把中位数放到 left
中。
代码
class MedianFinder {
PriorityQueue<Integer> left = new PriorityQueue<>((a, b) -> b - a);
PriorityQueue<Integer> right = new PriorityQueue<>((a, b) -> a - b);
public MedianFinder() {
}
public void addNum(int num) {
if(left.isEmpty()){
left.add(num);
return;
}
if(num > left.peek()){
right.add(num);
while(right.size() > left.size()){
left.add(right.poll());
}
}else{
left.add(num);
while(left.size() > right.size() + 1){
right.add(left.poll());
}
}
}
public double findMedian() {
if((left.size() + right.size()) % 2 == 1){
return 1.0 * left.peek();
}
return 1.0 * (left.peek() + right.peek()) / 2.0;
}
}