Thinking process

  • FIFO => Queue

Mistakes

  • be careful with whether add equal sign
public class MovingAverage {
    private Queue<Integer> q;
    private int size;
    private double sum;

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

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

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

results matching ""

    No results matching ""