Java 173ms solutions by keeping SUM


  • 0
    P

    public class MovingAverage {
    private int size,counter;
    private int[] data;
    private double sum;

    public MovingAverage(int size) {
        this.size = size;
        this.counter =0;
        this.sum = 0;
        data= new int[size];
    }
    
    public double next(int val) {
        counter++;
        sum = sum - data[(counter-1)%size] + val;
        data[(counter-1)%size]=val;
        return sum/Math.min(counter, size);
    }
    

    }


Log in to reply
 

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