Java straight forward solution


  • 0
    public class MovingAverage {
        Queue<Integer> path;
        int max;
        int step;
        /** Initialize your data structure here. */
        public MovingAverage(int size) {
            path = new LinkedList<Integer>();
            max = size;
            step = 0;
        }
        
        public double next(int val) {
            if(path.size() < max){
                path.add(val);
                step += val;
            }else{
                step -= path.peek();
                path.poll();
                path.add(val);
                step += val;
            }
            return path.size() < max ? (double)step / path.size() : (double)step / max;
        }
    }
    

Log in to reply
 

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