346. Moving Average from Data Stream

Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.

For example,
MovingAverage m = new MovingAverage(3);
m.next(1) = 1
m.next(10) = (1 + 10) / 2
m.next(3) = (1 + 10 + 3) / 3
m.next(5) = (10 + 3 + 5) / 3

思路: 用queue来装数字,并且需要一个capacity来保证处理超出size的情况。
如果超出了size,就把queue中第一个元素给poll. 然后对queue中的所有元素求平均值返回

public class MovingAverage {
    ArrayDeque<Integer> queue;
    int capacity;

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

    public double next(int val) {
        if (queue.size() >= capacity) {
            queue.poll();
        } 
        queue.offer(val);
        int sum = 0;
        double cnt = queue.size();
        Iterator iter = queue.iterator();
        while(iter.hasNext()) {
            sum = sum + (int)iter.next();
        }
        return sum / cnt;

    }
}

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