346. Moving Average from Data Stream

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
 

class MovingAverage {
    Queue<Integer> s = new LinkedList<Integer>();
    double d = 0;
    int xsize;
    /** Initialize your data structure here. */
    public MovingAverage(int size) {
        xsize = size;
    }
    
    public double next(int val) {
        d += val;
        
        if(s.size()>= xsize){
            d -= (double)s.poll();
        } 
        s.add(val);
        return d/s.size();
    }
}

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

喜欢的话订阅一个呗~第一时间收到文章更新哟~

发表评论

电子邮件地址不会被公开。