-
Notifications
You must be signed in to change notification settings - Fork 43
/
MovingAverageFromDataStream.java
76 lines (63 loc) · 2.19 KB
/
MovingAverageFromDataStream.java
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
74
75
76
package LeetCodeJava.Queue;
// https://leetcode.com/problems/moving-average-from-data-stream/
import java.util.ArrayDeque;
import java.util.Deque;
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/
public class MovingAverageFromDataStream {
// V1
// https://leetcode.com/problems/moving-average-from-data-stream/editorial/
int size, windowSum = 0, count = 0;
Deque queue = new ArrayDeque<Integer>();
public void MovingAverage(int size) {
this.size = size;
}
public double next(int val) {
++count;
// calculate the new sum by shifting the window
queue.add(val);
int tail = count > size ? (int)queue.poll() : 0;
windowSum = windowSum - tail + val;
return windowSum * 1.0 / Math.min(size, count);
}
// V2
// https://leetcode.com/problems/moving-average-from-data-stream/editorial/
class MovingAverage {
int size, windowSum = 0, count = 0;
Deque queue = new ArrayDeque<Integer>();
public MovingAverage(int size) {
this.size = size;
}
public double next(int val) {
++count;
// calculate the new sum by shifting the window
queue.add(val);
int tail = count > size ? (int)queue.poll() : 0;
windowSum = windowSum - tail + val;
return windowSum * 1.0 / Math.min(size, count);
}
}
// V2
// https://leetcode.com/problems/moving-average-from-data-stream/editorial/
class MovingAverage3 {
int size, head = 0, windowSum = 0, count = 0;
int[] queue;
public MovingAverage3(int size) {
this.size = size;
queue = new int[size];
}
public double next(int val) {
++count;
// calculate the new sum by shifting the window
int tail = (head + 1) % size;
windowSum = windowSum - queue[tail] + val;
// move on to the next head
head = (head + 1) % size;
queue[head] = val;
return windowSum * 1.0 / Math.min(size, count);
}
}
}