用Java自带的小顶堆PriorityQueue,改写Comparator的compare方法后可实现大顶堆。
注意大顶堆与小顶堆的元素差距不能超过1.
import java.util.*;
public class Solution {
PriorityQueue<Integer> minHeap=new PriorityQueue<Integer>();
PriorityQueue<Integer> maxHeap=new PriorityQueue<Integer>(20,new Comparator<Integer>(){
@Override
public int compare(Integer o1,Integer o2){
return o2-o1;
}
});
private int count=0;
public void Insert(Integer num) {
count++;
if(count%2==0){
if(!maxHeap.isEmpty()&&num<maxHeap.peek()){
maxHeap.add(num);
num=maxHeap.poll();
}
minHeap.add(num);
}else{
if(!minHeap.isEmpty()&&num>minHeap.peek()){
minHeap.add(num);
num=minHeap.poll();
}
maxHeap.add(num);
}
}
public Double GetMedian() {
if(maxHeap.size()==minHeap.size())
return (maxHeap.peek()+minHeap.peek())/2.0;
else if(maxHeap.size()>minHeap.size())
return maxHeap.peek()*1.0;
else
return minHeap.peek()*1.0;
}
}