-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path642.moving-average-from-data-stream.cpp
54 lines (49 loc) · 1.22 KB
/
642.moving-average-from-data-stream.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Tag: Data Stream, Sliding Window, Queue
// Time: O(1)
// Space: O(K)
// Ref: Leetcode-346
// Note: -
// Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
//
// **Example 1:**
// ```
// MovingAverage m = new MovingAverage(3);
// m.next(1) = 1 // return 1.00000
// m.next(10) = (1 + 10) / 2 // return 5.50000
// m.next(3) = (1 + 10 + 3) / 3 // return 4.66667
// m.next(5) = (10 + 3 + 5) / 3 // return 6.00000
// ```
//
//
class MovingAverage {
public:
/*
* @param size: An integer
*/
queue<int> q;
int size;
long long total;
MovingAverage(int size): size(size), total(0) {
// do intialization if necessary
}
/*
* @param val: An integer
* @return:
*/
double next(int val) {
// write your code here
q.push(val);
total += val;
if (q.size() > size) {
int cur = q.front();
q.pop();
total -= cur;
}
return double(total) / min(size, int(q.size()));
}
};
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param = obj.next(val);
*/