Skip to content

leet code

1368 - Moving Average from Data Stream

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class MovingAverage {
public:
    /** Initialize your data structure here. */
    MovingAverage(int size) {
        _size = size;
        _sum = 0.0;
    }

    double next(int val) {
        if(_q.size() >= _size)
        {
            _sum += val;
            _q.push(val);
            _sum -= _q.front();
            _q.pop();
        }else
        {
            _sum += val;
            _q.push(val);
        }
        return _sum/_q.size();
    }

private:
    queue<int> _q;
    int _size;
    double _sum;
};

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