Short Java solution


  • 0
    Y
    public class MovingAverage {
    
        int size, n, pos, sum;
        int[] w;
        
        public MovingAverage(int size) {
            this.size = size;
            w = new int[size];
            sum=0;
        }
        
        public double next(int val) {
            pos=pos % size;
            sum-=w[pos];
            w[pos++]=val;
            sum+=val;
            
            if(n<size)
                n++;
            return (double)sum/n;
        }   
    }
    

Log in to reply
 

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