剑指offer 41. 数据流中的中位数
题目描述
解题思路
参考题解:面试题41. 数据流中的中位数(优先队列 / 堆,清晰图解)
构造大顶堆时的写法:
maxHeap = new PriorityQueue<Integer>((x, y) -> (y - x));
这里的 (x, y) -> (y - x)
是 Java 8 的新特性 lamda 表达式,可以理解为一个简化的函数,函数的输入形参为 x 和 y,则输出为 return y - x。
这种写法等价于下面这样:
maxHeap = new PriorityQueue<Integer>(new Comparator<Integer>(){
public int compare(Integer num1, Integer num2) {
return num2 - num1;
}
});
本题具体代码如下:
class MedianFinder {
//小顶堆保存较大的元素,大顶堆保存较小的元素
private Queue<Integer> minHeap, maxHeap;
/** initialize your data structure here. */
public MedianFinder() {
minHeap = new PriorityQueue<Integer>();
maxHeap = new PriorityQueue<Integer>((x, y) -> (y - x));
}
public void addNum(int num) {
if (maxHeap.size() != minHeap.size()) {
//如果当前是奇数个元素,则需要往maxHeap中添加元素
minHeap.offer(num);
maxHeap.offer(minHeap.poll());
} else {
//如果当前是偶数个元素,则需要往minHeap中添加元素
maxHeap.offer(num);
minHeap.offer(maxHeap.poll());
}
}
public double findMedian() {
//如果是奇数,则返回minHeap的堆顶;如果是偶数,则返回两个堆堆顶的平均值
return maxHeap.size() != minHeap.size() ? (double)minHeap.peek() : (minHeap.peek() + maxHeap.peek()) / 2.0;
}
}
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/