Java solution


  • 0
    R

    Found this more intuitive.

    class MovingAverage {
        /** Initialize your data structure here. */
        Queue<Integer> q;
        int size = 0;
        double sum = 0;
        int len = 0;
        public MovingAverage(int size) {
            q= new LinkedList<Integer>();
            this.size = size;
        }
        
        public double next(int val) {
            if(len < size) {
                q.add(val);
                len++;
            } else {
                sum = sum - q.poll();
                q.add(val);
            }
            sum += val;
            return sum/len;
        }
    }
    

    Happy coding!! :)


Log in to reply
 

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