Java Simple Solution using Queue


  • 0
    M
    public class MovingAverage {
        long sum = 0;
        int maxSize = 0;
        Queue<Integer> q;
        /** Initialize your data structure here. */
        public MovingAverage(int size) {
            q = new LinkedList<>();
            maxSize = size;
        }
        
        public double next(int val) {
            sum += val;
            q.offer(val);
            if (q.size() > maxSize) {
                sum -= q.poll();
            }
            return sum / 1.0 / q.size();
        }
    }
    

Log in to reply
 

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