Java simple easy understand ArrayDeque solution beats 99.68% with explanation


  • 0
    Z

    We use use a queue to maintain current window element and sum to keep track of the sum of those element in the window.

    When the element come, we add to the queue, assume the queue is right in and left out, at the same time, we update the sum which adds the new element,

    When the queue size is greater than size, we remove the first element(or left element). At the same time, we update the sum which subtract the removed element..

    public class MovingAverage {
        private ArrayDeque<Integer> queue;
        private int size;
        private double sum;
    
        /** Initialize your data structure here. */
        public MovingAverage(int size) {
            this.queue = new ArrayDeque<Integer>();
            this.size = size;
            this.sum = 0;
        }
    
        public double next(int val) {
            queue.offer(val);
            sum += val;
            if (queue.size() > size) {
            	sum -= queue.removeFirst();
            }
        
    	    return sum / (size > queue.size() ? queue.size() : size);
        }
    }

Log in to reply
 

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