中位数是有序整数列表中的中间值。如果列表的大小是偶数,则没有中间值,中位数是两个中间值的平均值。
- 例如
arr = [2,3,4]
的中位数是3
。 - 例如
arr = [2,3]
的中位数是(2 + 3) / 2 = 2.5
。
实现 MedianFinder 类:
MedianFinder()
初始化MedianFinder
对象。void addNum(int num)
将数据流中的整数num
添加到数据结构中。double findMedian()
返回到目前为止所有元素的中位数。与实际答案相差10-5
以内的答案将被接受。
示例 1:
输入
["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
[[], [1], [2], [], [3], []]
输出
[null, null, null, 1.5, null, 2.0]
解释
MedianFinder medianFinder = new MedianFinder();
medianFinder.addNum(1); // arr = [1]
medianFinder.addNum(2); // arr = [1, 2]
medianFinder.findMedian(); // 返回 1.5 ((1 + 2) / 2)
medianFinder.addNum(3); // arr[1, 2, 3]
medianFinder.findMedian(); // return 2.0
提示:
-105 <= num <= 105
- 在调用
findMedian
之前,数据结构中至少有一个元素 - 最多
5 * 104
次调用addNum
和findMedian
//leetcode submit region begin(Prohibit modification and deletion)
class MedianFinder {
PriorityQueue<Integer> smallQ;
PriorityQueue<Integer> bigQ;
public MedianFinder() {
smallQ = new PriorityQueue<>(new Comparator<>(){
@Override
public int compare(Integer o1, Integer o2) {
return -o1.compareTo(o2);
}
});
bigQ = new PriorityQueue<>();
}
public void addNum(int num) {
Integer smallV = smallQ.peek();
Integer bigV = bigQ.peek();
if (smallV == null && bigV == null) {
smallQ.add(num);
} else if (num <= smallV) {
smallQ.add(num);
} else {
bigQ.add(num);
}
if (smallQ.size() - bigQ.size() > 1) {
bigQ.add(smallQ.poll());
} else if (bigQ.size() - smallQ.size() > 1) {
smallQ.add(bigQ.poll());
}
}
public double findMedian() {
if (smallQ.size() == bigQ.size()) {
return ((double)smallQ.peek() + (double)bigQ.peek())/2;
} else if (smallQ.size() > bigQ.size()) {
return smallQ.peek();
} else {
return bigQ.peek();
}
}
}
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/
//leetcode submit region end(Prohibit modification and deletion)