-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy path642.sliding-window-average-from-data-stream.java
More file actions
74 lines (57 loc) · 1.74 KB
/
642.sliding-window-average-from-data-stream.java
File metadata and controls
74 lines (57 loc) · 1.74 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
72
73
/* Initial Version */
public class MovingAverage {
private int size; // sliding window size
private int idx; // current index of the array
private int[] presum; // prefix sum
/** Initialize your data structure here. */
public MovingAverage(int size) {
this.size = size;
idx = 1;
presum = new int[100000];
}
public double next(int val) {
presum[idx] = val + presum[idx - 1];
if (idx <= size) {
double ans = (double) presum[idx] / idx;
idx++;
return ans;
}
double ans = 0;
ans = presum[idx] - presum[idx - size];
idx++;
return ans / size;
}
}
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param = obj.next(val);
*/
/* Final Version */
public class MovingAverage {
private int size; // sliding window size
private int idx; // current index of the array
private double[] presum; // prefix sum
/** Initialize your data structure here. */
public MovingAverage(int size) {
this.size = size;
idx = 0;
presum = new double[size+1];
}
private int mod(int idx) {
return idx % (size + 1);
}
public double next(int val) {
idx++;
presum[mod(idx)] = val + presum[mod(idx - 1)];
if (idx <= size) {
return presum[mod(idx)] / idx;
}
return (presum[mod(idx)] - presum[mod(idx - size)]) / size;
}
}
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param = obj.next(val);
*/