Java O(1) solution | Space : O(windowSize) Using Array


  • 0
    M
    public class MovingAverage {
        
        int size;
        int[] values;
        int idx;
        int sum;
    
        /** Initialize your data structure here. */
        public MovingAverage(int size) {
            this.size = size;
            this.values = new int[this.size];
        }
        
        public double next(int val) {
            if (this.size == 0) return 0;
            
            if (idx >= size) {
                // The array is full
                sum = sum - values[this.idx % this.size] + val;
                
                values[this.idx % this.size] = val;
                idx++;
                
                return (double)sum / (double) size;
            } else {
                sum += val;
                values[this.idx % this.size] = val;
                idx++;  
                
                return (double) sum / (double) idx;
            }
            
        }
    }
    

Log in to reply
 

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