295. Find Median from Data Strea
LeetCode Link
class MedianFinder {
private PriorityQueue<Integer> smallMaxHeap = null;
private PriorityQueue<Integer> bigMinHeap = null;
public MedianFinder() {
smallMaxHeap = new PriorityQueue<Integer>(10, Collections.reverseOrder());
bigMinHeap = new PriorityQueue<Integer>(10);
}
// keep smallMaxHeap.size euqal to (bigMinHeap.size or bigMinHeap.size + 1)
public void addNum(int num) {
if (smallMaxHeap.isEmpty() || num < smallMaxHeap.peek()) {
smallMaxHeap.offer(num);
if (smallMaxHeap.size() == bigMinHeap.size() + 2) {
bigMinHeap.offer(smallMaxHeap.poll());
}
} else {
bigMinHeap.offer(num);
if (bigMinHeap.size() > smallMaxHeap.size()) {
smallMaxHeap.offer(bigMinHeap.poll());
}
}
}
public double findMedian() {
if (smallMaxHeap.isEmpty()) {
return 0.0;
} else if (smallMaxHeap.size() == bigMinHeap.size()) {
return (smallMaxHeap.peek() + bigMinHeap.peek()) / 2.0;
}
return (double)smallMaxHeap.peek();
}
}
本文标题:295. Find Median from Data Strea
本文链接:https://www.haomeiwen.com/subject/oixcrftx.html
网友评论