JAVA Use Int Array As Window


  • 0
    Y
    public class MovingAverage {
        int[] window;
        int size;
        int cur;
        int sum;
        int count;
        /** Initialize your data structure here. */
        public MovingAverage(int size) {
            window = new int[size];
            this.size = size;
        }
        
        public double next(int val) {
            if(cur >= size)
                cur = 0;
            sum = sum - window[cur] + val;
            window[cur++] = val;
            count++;
            if(count >= size)
                count = size;
            return sum / (double)count;
        }
    }
    
    /**
     * 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.