题目描述
AC代码
/*
解题思路:可以通过对顶堆(大根堆和小根堆)来解决。
把一组数(假设N个数)分成两拨,大根堆和小根堆维护的个数尽量不超过1个(N/2),小根堆可以比大根堆多一个元素。
小根堆维护较大的N/2个数字,大根堆维护较小的N/2个数字,那么小根堆的top()和大根堆的top()就是这N个数中间的两个数了。
插入的时候:
1.如果大根堆是空的,或者要插入的元素num>=大根堆的top元素,那么就插入到小根堆中。
2.否则元素num就插入到大根堆中。
3.为了平衡大根堆和小根堆的元素个数尽量相差不超过一个,还需要加一个if判断,调节一下。
获取中位数的时候:
看一下元素总个数是奇数还是偶数。
*/
class MedianFinder {
//小根堆
Queue<Integer> up = new PriorityQueue<>();
//大根堆
Queue<Integer> down = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
/** initialize your data structure here. */
public MedianFinder() {
}
public void addNum(int num) {
if(down.isEmpty()||num>=down.peek())
up.offer(num);
else{
down.offer(num);
up.offer(down.poll());
}
if(up.size()>down.size()+1)
down.offer(up.poll());
}
public double findMedian() {
//判断是不是奇数
boolean flag=((up.size()+down.size())&1)==1?true:false;
if(flag) return up.peek();
else return (down.peek()+up.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();
*/