维护一个大顶堆和一个小顶堆(动态平衡二叉树的插入效率高,不会出现退化现象)
count表示这是第几个数,如果是偶数个放入右边的小顶堆,如果是奇数,放入左边的大顶堆。在放入之后要保证左边的大顶堆最大的数小于右边的小顶堆最小的数
TreeSet<Integer> min = new TreeSet<Integer>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
return o1 -o2;
}
});
TreeSet<Integer> max = new TreeSet<Integer>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
return o2 -o1;
}
});
int count = 0;
public void Insert(Integer num) {
count++;
if(count%2==0)
{
min.add(num);
if(max.size()!=0)
{
int maxTop = max.first();
int minTop = min.first();
if(maxTop>minTop)
{
max.remove(maxTop);
min.remove(minTop);
max.add(minTop);
min.add(maxTop);
}
}
}
else{
max.add(num);
if(min.size()!=0)
{
int maxTop = max.first();
int minTop = min.first();
if(maxTop>minTop)
{
max.remove(maxTop);
min.remove(minTop);
max.add(minTop);
min.add(maxTop);
}
}
}
}
public Double GetMedian() {
if(count%2==1)
{
return (double)max.first();
}
else{
return (double) ((max.first() + min.first()) / 2.0);
}
}