数据流中的中位数

数据流中的中位数

  1. 简单直接—用list存储,调用sort方法排序。
class MedianFinder {

    /** initialize your data structure here. */
    ArrayList<Integer> arrayList;
    public MedianFinder() {
        arrayList = new ArrayList<>();
    }
    public void addNum(int num) {
        arrayList.add(num);
    }
    public double findMedian() {
        int size = arrayList.size();
        Collections.sort(arrayList);
        if (size % 2 == 1) {
            return arrayList.get(size / 2);
        }
        else {
            int index = size / 2;
            int n1 = arrayList.get(index);
            int n2 = arrayList.get(index - 1);
            return (n1 + n2) / 2.0;
        }
    }
}
  1. 用大根堆和小根堆存储数据流中元素。
    大根堆存储比小根堆存储元素多1,并且大根堆元素小于小根堆元素。
    如果N为奇数,大根堆堆顶元素为中位数。
    如果N为偶数,大根堆堆顶元素和小根堆堆顶元素和的平均值为中位数。
class MedianFinder {
    /** initialize your data structure here. */
    PriorityQueue<Integer> min_heap;
    PriorityQueue<Integer> max_heap;
    public MedianFinder() {
        min_heap = new PriorityQueue<>();
        max_heap = new PriorityQueue<>((o1, o2) -> o2 - o1);
    }
    
    public void addNum(int num) {
        max_heap.add(num);
        if (!min_heap.isEmpty() && max_heap.peek() > min_heap.peek()) {
            int x = min_heap.poll();
            int y = max_heap.poll();
            min_heap.add(y);
            max_heap.add(x);
        }
        
        if (max_heap.size() > min_heap.size() + 1) {
            min_heap.add(max_heap.poll());
        }
    }

    public double findMedian() {
        if ((min_heap.size() + max_heap.size() & 1) == 1) {
            return max_heap.peek();
        }
        else {
            int x1 = min_heap.peek();
            int x2 = max_heap.peek();
            
            return (x1 + x2) / 2.0;
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值