脑子里建立如下动态的过程:为了找到添加新数据以后,数据流的中位数,我们让新数据在最大堆和最小堆中都走了一遍。而为了让最大堆的元素多 1 个,我们让从最小堆中又拿出一个元素「送回」给最大堆;
class MedianFinder {
//当前大堆顶和小堆顶的元素个数之和
private int count;
private PriorityQueue<Integer> maxheap;
private PriorityQueue<Integer> minheap;
/** initialize your data structure here. */
public MedianFinder() {
count=0;
/默认大顶堆 大顶堆存最小的k个数
maxheap=new PriorityQueue<>((x,y)->y-x);
//默认小顶堆 小顶堆存最大的k个数
minheap=new PriorityQueue<>();
}
public void addNum(int num) {
count+=1;
maxheap.offer(num);
minheap.offer(maxheap.poll());
if(count%2!=0){
maxheap.offer(minheap.poll());
}
}
public double findMedian() {
if(count%2==0){
return (double)(maxheap.peek()+minheap.peek())/2;
}else{
return (double)maxheap.peek();
}
}
}
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/