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 Stream
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- leetcode two heap use two heap is quite straight forward....
- My Submissions Difficulty: Hard Median is the middle valu...
- Median is the middle value in an ordered integer list. If...
- Median is the middle value in an ordered integer list. If...