-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathMovingAverage.cpp
38 lines (33 loc) · 884 Bytes
/
MovingAverage.cpp
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
35
36
37
38
// Problem: https://leetcode.com/problems/moving-average-from-data-stream/
#include <vector>
using namespace std;
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage* obj = new MovingAverage(size);
* double param_1 = obj->next(val);
*/
class MovingAverage {
public:
MovingAverage(int size) {
_sum = 0;
_max_size = size;
_curr_size = 0;
}
double next(int val) {
if (_buffer.size() < _max_size) {
_sum += val;
_buffer.push_back(val);
++_curr_size;
} else {
_sum += val - _buffer[0];
_buffer.erase(_buffer.begin());
_buffer.push_back(val);
}
return (double)_sum/(double)_curr_size;
}
private:
vector<int> _buffer;
int _sum;
int _max_size;
int _curr_size;
};