您的位置 首页 JAVA(2017)

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);
 */
看完了?留个评分呗?
[0人评了分,平均: 0/5]

本站原创文章皆遵循“署名-非商业性使用-相同方式共享 3.0 (CC BY-NC-SA 3.0)”。转载请保留以下标注:

原文来源:《346. Moving Average from Data Stream》

发表评论

邮箱地址不会被公开。

返回顶部