public class Solution {
private int count = 0;
private PriorityQueue<Integer> minHeap = new PriorityQueue<>();
private PriorityQueue<Integer> maxHeap = new PriorityQueue<>(15, new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});//15是队列容量的大小
public void Insert(Integer num) {
//当此时共有偶数个元素时,新加入的元素先进入最大堆,筛选出最大元素后,加入最小堆,所以最小堆放的都是大数
if (count % 2 == 0) {
maxHeap.offer(num);
int filered = maxHeap.poll();
minHeap.offer(filered);
} else {
//当此时共有奇数个元素时,新加入的元素先进入最小堆,筛选出最小元素后,加入最大堆,所以最大堆放的都是小数
minHeap.offer(num);
int filered = minHeap.poll();
maxHeap.offer(filered);
}
count++;
}
public Double GetMedian() {
if (count % 2 == 0)
return new Double( (minHeap.peek() + maxHeap.peek()) ) / 2;
else
return new Double(minHeap.peek()); //总数为奇数个的时候,最小堆里的是中位数
}
}