JAVA SIMPLE O(1) SOLUTION, BEATS 94%


  • 0
    W

    public class MovingAverage {

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

    }

    /**

    • Your MovingAverage object will be instantiated and called as such:
    • MovingAverage obj = new MovingAverage(size);
    • double param_1 = obj.next(val);
      */

Log in to reply
 

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