47:数据流中的中位数

数据流中的中位数

public class Offer47 {

    //默认最小堆实现
    PriorityQueue<Integer> maxHeap = new PriorityQueue<>();
    //实现最大堆需要重写Comparator
    PriorityQueue<Integer> minHeap = new PriorityQueue<>(10, new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return o2.compareTo(o1);
        }
    });
    int count = 0;
    public void insert(Integer data){
        //如果为奇个数,插入最大堆
        if((count&1)==1){
            //最小堆不为空且插入数值大于最小堆的最大值
            if(!minHeap.isEmpty()&&data>minHeap.peek()){
                minHeap.offer(data);
                //弹出最小值
                data = minHeap.poll();
            }
            maxHeap.offer(data);
        }else {
            //如果为偶个数,插入最小堆
            //最大堆不为空且插入数组小于最大堆的最大值
            if(!maxHeap.isEmpty()&&data<maxHeap.peek()){
                minHeap.offer(data);
                data = maxHeap.poll();
            }
            minHeap.offer(data);
        }
        count++;
    }

    public double getMedian(){
        if((count&1)==0){
            return (maxHeap.peek()*minHeap.peek())/2.0;
        }else{
            return maxHeap.peek()*1.0;
        }

    }
}

你可能感兴趣的:(剑指offer)