码迷,mamicode.com
首页 > 其他好文 > 详细

346. Moving Average from Data Stream

时间:2016-07-12 11:49:25      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

/*
 * 346. Moving Average from Data Stream
 * 2016-7-11 by Mingyang
 * 这里注意的就是(double) sum / count
 * sum需要转换成double才能继续往下除,因为不转的话最后不能成为整数14除以3等于4
 */
class MovingAverage {
    public Queue<Integer> queue;
    public int sum = 0;
    public int si;
    public int count = 0;

    /** Initialize your data structure here. */
    public MovingAverage(int size) {
        this.si = size;
        queue = new LinkedList<Integer>();
    }

    public double next(int val) {
        if (queue.size() < si) {
            queue.add(val);
            sum += val;
            count++;
        } else {
            int temp = queue.poll();
            sum -= temp;
            queue.add(val);
            sum += val;
        }
        return (double) sum / count;
    }
}

 

346. Moving Average from Data Stream

标签:

原文地址:http://www.cnblogs.com/zmyvszk/p/5662687.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!