Moving Average from Data Stream

https://leetcode.com/problems/moving-average-from-data-stream/description/

Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.

For example,

MovingAverage m = new MovingAverage(3);

m.next(1) = 1

m.next(10) = (1 + 10) / 2

m.next(3) = (1 + 10 + 3) / 3

m.next(5) = (10 + 3 + 5) / 3

Thoughts

思路很直观, 用一个queue把新的加进去老的扔出去. 为了计算average, 需要不断更新window sum. 还可以用array和mod模拟queue的效果.

Code

class MovingAverage {
    int insert, count;
    long sum;
    int[] window;
    /** Initialize your data structure here. */
    public MovingAverage(int size) {
        insert = 0;
        count = 0;
        sum = 0;
        window = new int[size];
    }

    public double next(int val) {
        if (count < window.length) {
            count++;
        }

        sum -= window[insert];
        window[insert] = val;
        sum += val;
        insert = (insert + 1) % window.length;
        return (double)(sum) / count;
    }
}

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

Analysis

时空复杂度O(N).

Last updated