数据流滑动窗口平均值(LintCode题目)

背景

领扣(LintCode)的题目,自己写一个 ,参照其他人的写一个

自己的代码: 总耗时 3686 ms
public class MovingAverage {
    private int size;
    private Queue<Integer> queue;
    /*
    * @param size: An integer
    */public MovingAverage(int size) {
        // do intialization if necessary
        this.size=size;
        queue=new ArrayDeque(size);
    }

    /*
     * @param val: An integer
     * @return:  
     */
    public double next(int val) {
        // write your code here
        int length;
        double result=0.00000;
        if((length=queue.size())==size){//判断队列是否已满
            queue.poll();
            queue.add(val);
            Iterator iterator=queue.iterator();
            while(iterator.hasNext()){
                result+=(Integer)iterator.next();
                }
            return result/length;
        }else{
            queue.add(val);
            length=queue.size();
            Iterator iterator=queue.iterator();
            while(iterator.hasNext()){
                result+=(Integer)iterator.next();
            }
           return result/length;
        }
    }
   
}
别人的代码:总耗时 1732 ms
public class MovingAverage {
    private final int maxSize;
    private final Queue<Integer> window;
    private long sum = 0;
    
    public MovingAverage(int maxSize) {
        this.maxSize = maxSize;
        this.window = new ArrayDeque<>(maxSize + 1);
    }

    public double next(int val) {
        window.add(val);
        sum += val;
        if (window.size() > maxSize) {
            sum -= window.poll();
        }
        return (double) sum / window.size();
    }
}
感悟

这就是差距吗,笑哭。。。。。
而且这个还不是最好的。。(只超过60%的人)
看来自己还是任重而道远,加油吧,骚年

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值