Simple Java solution beats 80% using ArrayList.


  • 0
    public class MovingAverage {
    private int sum;
    private int mysize;
    private List<Integer> store;
    /** Initialize your data structure here. */
    public MovingAverage(int size) {
        sum = 0;
        mysize = size;
        store = new ArrayList<>();
    }
    public double next(int val) {
        if(store.size()<mysize){
            store.add(val);
            sum+=val;
            return (double)sum/store.size();
        }
        else{
            sum = sum - store.get(0) + val;
            store.remove(0);
            store.add(val);
            return (double)sum/mysize;
        }
    }
    }
    
    /**
    * Your MovingAverage object will be instantiated and called as such:
    * MovingAverage obj = new MovingAverage(size);
    * double param_1 = obj.next(val);
    */

Log in to reply
 

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