实时中位数

题目描述
现有一些随机生成的数字要将其依次传入,请设计一个高效算法,对于每次传入一个数字后,算出当前所有传入数字的中位数。(若传入了偶数个数字则令中位数为第n/2小的数字,n为已传入数字个数)。

给定一个int数组A,为传入的数字序列,同时给定序列大小n,请返回一个int数组,代表每次传入后的中位数。保证n小于等于1000。

测试样例:
[1,2,3,4,5,6],6
返回:[1,1,2,2,3,3]

构建一个最大堆 一个最小堆 保持 最大堆的size >= 最小堆的size 且差值不超过1,且最大堆的堆顶小于最小堆的堆顶

每次返回最大堆的堆顶

import java.util.*;

public class Middle {
    public int[] getMiddle(int[] A, int n) {
        // write code here
       // write code here
        PriorityQueue<Integer> min_heap = new PriorityQueue<Integer>();
        PriorityQueue<Integer> max_heap = new PriorityQueue<Integer>(new Comparator<Integer>() {
        	@Override
        	public int compare(Integer o1, Integer o2) {
        		return o2-o1;
        	}
        });
        int [] m = new int[n];
        
        for(int i=0; i<n; i++) {
        	if(max_heap.size()==0 || A[i]<max_heap.peek())
        		max_heap.add(A[i]);
        	else
        		min_heap.add(A[i]);
        	if(max_heap.size() == min_heap.size()+2) {
        		int a = max_heap.poll();
        		min_heap.add(a);
        	}
        	if(max_heap.size()+1 == min_heap.size()) {
        		max_heap.add(min_heap.poll());
        	}
        	m[i] = max_heap.peek();
        }
        
        return m;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值