描述
如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。
例如,
[2,3,4] 的中位数是 3
[2,3] 的中位数是 (2 + 3) / 2 = 2.5
设计一个支持以下两种操作的数据结构:
void addNum(int num) - 从数据流中添加一个整数到数据结构中。
double findMedian() - 返回目前所有元素的中位数。
分析
使用堆求中间值,难的是堆的大小总是在变,中间值不确定,所以用一个堆很难求(反正我不会)。
解决办法:使用两个堆,一个大顶堆,一小顶堆,大顶堆保存前半部,小顶堆保存后半部分的数。中位数就是从两个栈的栈顶取。
注意,每次插入一个数,两个堆都有插入操作,确保两个堆整体上有序。
class MedianFinder {
PriorityQueue<Integer> bigheap;
PriorityQueue<Integer> smallheap;
public MedianFinder() {
bigheap = new PriorityQueue<>((a,b)->Integer.compare(b,a));
smallheap = new PriorityQueue<>((a,b)->Integer.compare(a,b));
}
public void addNum(int num) {
if(smallheap.size() > bigheap.size()){
smallheap.offer(num);
int tmp = smallheap.poll();
bigheap.offer(tmp);
}else{
bigheap.offer(num);
int tmp = bigheap.poll();
smallheap.offer(tmp);
}
}
public double findMedian() {
if(bigheap.size() == smallheap.size()){
return (double)(bigheap.peek() + smallheap.peek())/2.0;
}else{
return (double)smallheap.peek();
}
}
}
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/