BM48 数据流中的中位数

在这里插入图片描述
解题思路:当数据流中数字数目是奇数是,小根堆中多一个数字,当数据流中数字数目是偶数时,小根堆和大根堆中数字数目一样多。但是小根堆中保存的数字都要从大根堆中出,大根堆中的数字都要从小根堆中出,这样才能保证小根堆和大根堆中的根是中位数

import java.util.*;
public class Solution {

    //大根堆
    PriorityQueue<Integer> maxQueue = new PriorityQueue<>((o1, o2)->o2 - o1);
    //小根堆
    PriorityQueue<Integer> minQueue = new PriorityQueue<>((o1, o2)->o1 - o2);
    int size = 0;
    public void Insert(Integer num) {
        if ((size & 1) != 1 ) {
            maxQueue.offer(num);
            minQueue.offer(maxQueue.poll());
        } else {
            minQueue.offer(num);
            maxQueue.offer(minQueue.poll());
        }
        size++;
    }

    public Double GetMedian() {
        if ((size & 1) != 1 ) {
            return ((double)minQueue.peek() + (double)maxQueue.peek()) / 2;
        } else {
            return (double)minQueue.peek();
        }
    }
}

解法二:先排序后取中位数

import java.util.*;
public class Solution {

    ArrayList<Integer> list = new ArrayList<>();
    public void Insert(Integer num) {
        list.add(num);
    }

    public Double GetMedian() {
        Collections.sort(list);
        int size = list.size();
        if ((size & 1) != 1) {
            return ((double)list.get(size / 2) + (double)list.get(size / 2 - 1)) / 2;
        } else {
            return (double)list.get(size / 2);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值