java
复制代码
class MedianFinder {
//A为小根堆,B为大根堆
List<Integer> A,B;
public MedianFinder() {
A = new ArrayList<Integer>();
B = new ArrayList<Integer>();
}
public void addNum(int num) {
int m = A.size(),n = B.size();
if(m == n){
insert(B,num);
int top = deleteTop(B);
insert(A,top);
}else{
insert(A,num);
int top = deleteTop(A);
insert(B,top);
}
}
//删除堆顶元素并返回其值
private int deleteTop(List<Integer> list){
Collections.swap(list,0,list.size() - 1);
int heapSize = list.size() - 1;
int root = 0;
while(root < heapSize/2){
int left = root * 2 + 1,right = root * 2 + 2,largest = root;
if(left < heapSize && comparee(list,left,largest))
largest = left;
if(right < heapSize && comparee(list,right,largest))
largest = right;
if(root == largest)
break;
Collections.swap(list,root,largest);
root = largest;
}
return list.remove(list.size() - 1);
}
//A小根堆的比较方法:比较值<目标值?
private boolean comparee(List<Integer> list,int source,int target){
if(list == A)
return list.get(source) < list.get(target);
else
return list.get(source) > list.get(target);
}
//将数插入到堆中
private void insert(List<Integer> list,int num){
list.add(num);
int index = list.size() - 1;
while(index > 0){
int root = (index - 1) / 2;
if(!comparee(list,index,root))
break;
Collections.swap(list,root,index);
index = root;
}
}
public double findMedian() {
int m = A.size(),n = B.size();
return (m==n) ? (A.get(0) + B.get(0)) / 2.0 : A.get(0);
}
}