140ms Java, Concise Solution w/ Queue

  • 0

    The idea is to use a Queue to maintain the current window. The reason we use a Queue is because we need the FIFO property. We want to have access to the "oldest" element in the Queue.

    The idea is as follows: if we have hit our max size, we will poll from the Queue and subtract from our sum. If we haven't hit our max size, we just do a standard add to the sum. In both cases, we add our new value to our Queue.

    public class MovingAverage {
        private Queue<Integer> q;
        private int maxSize;
        private double sum;
        /** Initialize your data structure here. */
        public MovingAverage(int size) {
            this.q = new LinkedList<Integer>();
            this.maxSize = size;
            this.sum = 0;
        public double next(int val) {
            sum = val + (q.size() == maxSize ? sum - q.poll() : sum);
            return sum / q.size();
     * Your MovingAverage object will be instantiated and called as such:
     * MovingAverage obj = new MovingAverage(size);
     * double param_1 = obj.next(val);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.