数据流中位数

数字是不断进入数组的,在每次添加一个新的数进入数组的同时返回当前新数组的中位数。
中位数的定义:
中位数是排序后数组的中间值,如果有数组中有n个数,则中位数为A[(n-1)/2]。
比如:数组A=[1,2,3]的中位数是2,数组A=[1,19]的中位数是1。
样例
持续进入数组的数的列表为:[1, 2, 3, 4, 5],则返回[1, 1, 2, 2, 3]

时间复杂度为O(nlogn)

private PriorityQueue<Integer> minheap, maxheap;
    private int numOfElement = 0;
    
    
    public int[] medianII(int[] nums) {
        
        Comparator <Integer> rev = new Comparator/*<>*/<Integer>(){
            @Override
            public int compare(Integer left, Integer right){
                return right.compareTo(left);
            }
        };
        int count = nums.length;
        maxheap = new PriorityQueue<Integer>(count, rev);
        minheap = new PriorityQueue<Integer>(count);
        int []ans = new int[count];
        for(int i=0; i<count; i++){
            addNumber(nums[i]);
            ans[i]=getMedian();
            
        }
        return ans;
        
    }
    public void addNumber(int k){
        maxheap.offer(k);
        if(numOfElement % 2==0){
            if(minheap.size()== 0){
                numOfElement++;
                return;
            }else if(maxheap.peek() > minheap.peek()){
                Integer max = maxheap.poll();
                Integer min = minheap.poll();
                maxheap.offer(min);
                minheap.offer(max);
            }
        }else{
            minheap.offer(maxheap.poll());
        }
        numOfElement++;
    }
    public int getMedian(){
        return maxheap.peek();
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值