Easy java solution with linked list


  • 0
    W

    Using Java built in LinkedList, to remove the need to keep track of our own array window with index pointer

    class MovingAverage {
    
        LinkedList<Integer> list;
        int capacity;
        double total;
        
        /** Initialize your data structure here. */
        public MovingAverage(int size) {
            list = new LinkedList<Integer>();
            capacity = size;
            total = 0;
        }
        
        public double next(int val) {
            if (list.size() == capacity) total -= list.removeFirst();
            list.addLast(val);
            total += val;
            return total / list.size();
        }
    }
    

Log in to reply
 

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