Leetcode - Moving Average from Data Stream

My code:

public class MovingAverage {
    Queue<Integer> q = new LinkedList<Integer>();
    int size = 0;
    int sum = 0;
    /** Initialize your data structure here. */
    public MovingAverage(int size) {
        this.size = size;
    }
    
    public double next(int val) {
        if (q.size() < size) {
            q.offer(val);
            sum += val;
            return sum / (q.size() * 1.0);
        }
        else {
            Integer out = q.poll();
            sum -= out;
            sum += val;
            q.offer(val);
            return sum / (q.size() * 1.0);
        }
    }
}

/**
 * Your MovingAverage object will be instantiated and called as such:
 * MovingAverage obj = new MovingAverage(size);
 * double param_1 = obj.next(val);
 */

算是简答题吧。但也是惭愧。一开始想到的是用 ArrayList来做。。。
猪吗,那空间开销多大啊。。。
然后点 tag,发现用Queue, 一下子明白了。

Anyway, Good luck, Richardo! — 09/12/2016

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/abdd5a6c7584#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞