剑指 Offer 41. 数据流中的中位数

package leetcode;

import java.util.Comparator;
import java.util.PriorityQueue;

public class offer_41 {
    private PriorityQueue<Integer> big;
    private PriorityQueue<Integer> small;
    public offer_41(){
        //创建一个大顶堆,用于存储排序数组左边部分
         big=new PriorityQueue<Integer>(new Comparator<Integer>() {
            public int compare(Integer a,Integer b) {
                return b-a;
            }
        });
        //创建一个小顶堆,用于存储排序数组右边部分
        small=new PriorityQueue<Integer>();
    }
    public void addNum(int num) {
        //每次加入数组先加入大顶堆,然后将大顶堆中的最大值放入小顶堆,判断小顶堆中元素个数是否大于大顶堆中的元素个数,调整小顶堆元素进入大顶堆
        big.offer(num);
        small.offer(big.poll());
        if((small.size()-big.size())>1) {
            big.offer(small.poll());
        }
    }
    
    public double findMedian() {
        //如果两个堆元素个数相等,则中位数是两个堆的根节点的平均值
        if(big.size()==small.size()) {
            return ((double)big.peek()+(double)small.peek())/2;
        }
        else {
            //否则是小顶堆的根节点值
            return (double)small.peek();
        }
    }


}

 

posted on 2022-03-18 11:06  一仟零一夜丶  阅读(19)  评论(0)    收藏  举报