import java.util.Comparator;
import java.util.PriorityQueue;
public class MedianFinder {
private PriorityQueue<Integer> min = new PriorityQueue<Integer>();
private PriorityQueue<Integer> max = new PriorityQueue<Integer>(new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
//统计数据流的个数
private int count = 0;
//确保小根堆里面的数 > 大根堆里面的数
public void insert(Integer num) {
count++;
if (count % 2 == 1) {
//奇数的时候,放在小根堆里面
max.offer(num);//先从大顶堆过滤一遍
min.offer(max.poll());
} else {
//偶数的时候,放在大根堆里面
min.offer(num);//先从小顶堆过滤一遍
max.offer(min.poll());
}
}
public Double getMedian() {
if (count % 2 == 0) return (min.peek() + max.peek()) / 2.0;
else return (double) min.peek();
}
}