?力扣(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();
*/