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);
 */

This site Original article All followed" Attribution—NonCommercial—ShareAlike 4.0 (CC BY-NC-SA 4.0) ”。 Please keep the following marks for sharing and interpretation:

Original author: Jake Tao Source: 「346. Moving Average from Data Stream」

Praise 134
0 0 134

Further reading

Post a reply

Log in can only be commented on later
Share this page
Back to top