Simple O(1) Java solution


  • 3
    N

    Maintain a sum and count for elements in queue.

    public class MovingAverage {
    
        /** Initialize your data structure here. */
        Queue queue = new LinkedList();
        int size;
        int count;
        int sum;
        
        public MovingAverage(int size) {
            this.size = size;
        }
        
        public double next(int val) {
            if (count == size) {
                sum = sum - (int)queue.remove();
                sum += val;
                queue.add(val);
            } else {
                count++;
                sum += val;
                queue.add(val);
            }
            return (double)(sum)/(double)(count);
        }
    }
    

Log in to reply
 

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