关于我的 Leetcode 题目解答,代码前往 Github:https://github.com/chenxiangcyr/leetcode-answers
Leetcode: Find Median from Data Stream
使用两个堆
- A max-heap 最大堆 to store the smaller half of the input numbers
- A min-heap 最小堆 to store the larger half of the input numbers
class MedianFinder {
// store the smaller half of the input numbers
private PriorityQueue<Integer> maxHeap;
// store the larger half of the input numbers
private PriorityQueue<Integer> minHeap;
/** initialize your data structure here. */
public MedianFinder() {
// Should provide comparator to support max heap
maxHeap = new PriorityQueue<Integer>(Collections.reverseOrder());
// by default, PriorityQueue is a min heap
minHeap = new PriorityQueue<Integer>();
}
public void addNum(int num) {
maxHeap.add(num);
// balancing
minHeap.add(maxHeap.peek());
maxHeap.poll();
// maintain size property
if(maxHeap.size() < minHeap.size()) {
maxHeap.add(minHeap.peek());
minHeap.poll();
}
}
public double findMedian() {
if((maxHeap.size() + minHeap.size()) % 2 == 0) {
return (maxHeap.peek() + minHeap.peek()) / 2.0;
}
else {
return maxHeap.peek();
}
}
}