-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLeetCode-346-Moving-Average-from-Data-Stream.java
More file actions
50 lines (43 loc) · 1.19 KB
/
LeetCode-346-Moving-Average-from-Data-Stream.java
File metadata and controls
50 lines (43 loc) · 1.19 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
class MovingAverage {
// 1. Using Queue
// int size;
// double sum;
// Queue<Integer> queue;
// /** Initialize your data structure here. */
// public MovingAverage(int size) {
// this.size = size;
// this.sum = 0.0;
// this.queue = new LinkedList<>();
// }
// public double next(int val) {
// if (queue.size() >= size) {
// sum -= queue.poll();
// }
// queue.add(val);
// sum += val;
// return sum / queue.size();
// }
// 2. Using an Array
int n, pointer;
double sum;
int[] window;
/** Initialize your data structure here. */
public MovingAverage(int size) {
this.n = 0;
this.pointer = 0;
this.sum = 0.0;
this.window = new int[size];
}
public double next(int val) {
sum = sum - window[pointer] + val;
window[pointer] = val;
pointer = (pointer + 1) % window.length;
if (n < window.length) n++;
return sum / n;
}
}
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/