- Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathMovingAverageFromDataStream346.java
More file actions
Latest commit
72 lines (60 loc) · 1.9 KB
/
Copy pathMovingAverageFromDataStream346.java
File metadata and controls
72 lines (60 loc) · 1.9 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* 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
*/
publicclassMovingAverageFromDataStream346 {
classMovingAverage {
privateintsize;
privateQueue<Integer> cache;
privatelongsum;
/** Initialize your data structure here. */
publicMovingAverage(intsize) {
this.size = size;
this.cache = newLinkedList<Integer>();
this.sum = 0L;
}
publicdoublenext(intval) {
if (this.cache.size() >= this.size) {
this.sum -= this.cache.remove();
}
this.sum += val;
this.cache.add(val);
returnthis.sum * 1.0 / this.cache.size();
}
}
classMovingAverage2 {
privateint[] window;
privateinthead = 0;
privateintlen = 0 ;
privateintsum = 0;
/** Initialize your data structure here. */
publicMovingAverage2(intsize) {
this.window = newint[size + 1];
}
publicdoublenext(intval) {
intnextPos = (this.head + this.len + 1) % this.window.length;
this.window[nextPos] = val;
this.len++;
this.sum += val;
if (this.len == this.window.length) {
this.head++;
this.head %= this.window.length;
this.len--;
this.sum -= this.window[this.head];
}
returnthis.sum * 1.0 / this.len;
}
}
}
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/