数据流中的中位数

思想:
建立两个排序碓(优先队列),大根堆和小根堆。

  1. 个数为奇数时,元素存大根堆,放count-count/2的小数。
  2. 个数为偶数时,元素存小根堆,放count/2的大数。

当个数为奇数时

if(元素>小根堆的堆顶)
    swap(元素,小根堆的堆顶)
元素加入大根堆

偶数时

if(元素<大根堆的堆顶)
    swap(元素,大根堆的堆顶)
元素加入小根堆

代码如下

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

public class Solution {
    PriorityQueue<Integer>queueMax=new PriorityQueue<>(new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return o2-o1;//从大到小
        }
    });
    PriorityQueue<Integer>queueMin=new PriorityQueue<>();
    int count=0;
    public void Insert(Integer num) {
        count++;
        if(count%2==1){
            if(queueMin.isEmpty()==false&&num>queueMin.peek()){
                queueMin.offer(num);
                num=queueMin.poll();
            }
            queueMax.offer(num);
        }
        else {
            if(queueMax.isEmpty()==false&&num<queueMax.peek()){
                queueMax.offer(num);
                num=queueMax.poll();
            }
            queueMin.offer(num);
        }
    }

    public Double GetMedian() {
            if(count%2==1){
                return (double)queueMax.peek();
            }
            else {
                return (double)(queueMax.peek()+queueMin.peek())/2.0;
            }
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值