I don't know why I'm wrong(Java Solution)


  • 0
    L
    public int[] window;
    public int index;
    public int total;
    
    /** Initialize your data structure here. */
    public MovingAverage(int size) {
        this.index = 0;
        this.window = new int[size];
        this.total = 0;
    }
    
    public double next(int val) {
        if(this.index < this.window.length){
            this.window[this.index] = val;
            this.index++;
            this.total += val;
        }else if(this.index == this.window.length){
            this.total += (val - this.window[0]);
            for(int i = 0; i < this.window.length; i++){
                if(i != this.window.length - 1){
                    this.window[i] = this.window[i + 1];
                }else{
                    this.window[i] = val;
                }
            }
        }
        return this.total / this.index;
    }
    

    Always report TLE in the submission report


  • 0

    Your solution takes O(W) time to calculate moving average. You should take O(1) time for next() and O(W) additional space. Check out https://leetcode.com/discuss/110760/simple-python-solution-based-on-circular-array-o-next-space


  • 0
    L

    Thanks! I haven't thought about this problem.


Log in to reply
 

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