美文网首页
346. Moving Average from Data St

346. Moving Average from Data St

作者: matrxyz | 来源:发表于2018-01-17 13:05 被阅读0次

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

Solution:

思路:

Time Complexity: O(N) Space Complexity: O(N)

Solution Code:

public class MovingAverage {
    private int [] window;
    private int n, insert;
    private long sum;
    
    /** Initialize your data structure here. */
    public MovingAverage(int size) {
        window = new int[size];
        insert = 0;
        sum = 0;
    }
    
    public double next(int val) {
        if (n < window.length)  n++;
        sum -= window[insert];
        sum += val;
        window[insert] = val;
        insert = (insert + 1) % window.length;
        
        return (double)sum / n;
    }
}

相关文章

网友评论

      本文标题:346. Moving Average from Data St

      本文链接:https://www.haomeiwen.com/subject/ntzyoxtx.html