Skip to content

Commit 9750986

Browse files
EASY/src/easy/MovingAveragefromDataStream.java
1 parent a1ea793 commit 9750986

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package easy;
2+
3+
import java.util.LinkedList;
4+
import java.util.Queue;
5+
6+
public class MovingAveragefromDataStream {
7+
8+
}
9+
10+
class MovingAverage {
11+
12+
private Queue<Integer> q;
13+
private Long sum;
14+
private int max;
15+
16+
/** Initialize your data structure here. */
17+
public MovingAverage(int size) {
18+
q = new LinkedList();
19+
sum = 0l;
20+
max = size;
21+
}
22+
23+
public double next(int val) {
24+
if(q.size() < max){
25+
q.offer(val);
26+
sum += val;
27+
return (double) sum/q.size();
28+
} else {
29+
int first = q.poll();
30+
sum -= first;
31+
q.offer(val);
32+
sum += val;
33+
return (double) sum/q.size();
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)