Leetcode295 Find Median from Data Stream解题方法

Leetcode295 Find Median from Data Stream

题目描述

Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.

For example,

[2,3,4]`, the median is `3
[2,3]`, the median is `(2 + 3) / 2 = 2.5

Design a data structure that supports the following two operations:

  • void addNum(int num) - Add a integer number from the data stream to the data structure.
  • double findMedian() - Return the median of all elements so far.

Example:

addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3) 
findMedian() -> 2

思路

两个priority queue,一个queue存较大部分一个queue寸较小部分

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-59HqwTMC-1591387922329)(C:\Users\wangq\AppData\Roaming\Typora\typora-user-images\image-20200510102429767.png)]

较小部分:small = new PriorityQueue((a,b) -> a - b);

较大部分:large = new PriorityQueue((a,b) -> b - a);

加入元素:如果large部分为空或者num数大于large的最小元素,则将num加入到large中,反之加入small中。加入后,比较large和small的大小,两个队列的size差不能超多1

计算中位数:如果small和large的大小相同,则取small的最大和large的最小值相加除以2.0;如果small的数量多,则取small数组的最大的那个。

代码

class MedianFinder {
    
    Queue<Integer> small;
    Queue<Integer> large;
    /** initialize your data structure here. */
    public MedianFinder() {
        small = new PriorityQueue<Integer>((a,b) -> b - a);
        large = new PriorityQueue<Integer>((a,b) -> a - b);
    }
    
    public void addNum(int num) {
        if(small.isEmpty()||num<=small.peek()){
            small.add(num);
        }else{
            large.add(num);
        }
        //balance left and right
        if(small.size()-large.size()>1){
            large.add(small.poll());
        }else if(small.size()<large.size()){
            small.add(large.poll());
        }
    }
    
    public double findMedian() {;
        double media =0;
        if(large.size()==small.size())
            media = (small.peek()+large.peek())/2.0;
        else
            media = small.peek();
        return media;
    }
}

/**
 * Your MedianFinder object will be instantiated and called as such:
 * MedianFinder obj = new MedianFinder();
 * obj.addNum(num);
 * double param_2 = obj.findMedian();
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值