Java solution with Array / T : O(1), S : O(1)


  • 0
    J
    int size;
        List<Integer> lst;
        /** Initialize your data structure here. */
        public MovingAverage(int size) {
            this.size = size;
            this.lst = new ArrayList<Integer>();
        }
        
        public double next(int val) {
            if(lst.size() >= size){
                lst.remove(0);
            }
            
            lst.add(val);
            return lst.stream().mapToInt(value -> value).sum() / (double)lst.size();
        }
    

Log in to reply
 

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