Skip to content

Commit 603bc20

Browse files
refactor 346
1 parent 2b6b2c6 commit 603bc20

File tree

1 file changed

+30
-25
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+30
-25
lines changed

src/main/java/com/fishercoder/solutions/_346.java

Lines changed: 30 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@
33
import java.util.LinkedList;
44
import java.util.Queue;
55

6-
/**Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
6+
/**
7+
* 346. Moving Average from Data Stream
8+
*
9+
* Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
710
811
For example,
912
MovingAverage m = new MovingAverage(3);
@@ -14,33 +17,35 @@
1417
*/
1518
public class _346 {
1619

17-
class MovingAverage {
20+
public static class Solution1 {
21+
class MovingAverage {
1822

19-
private Queue<Integer> q;
20-
private Long sum;
21-
private int max;
23+
private Queue<Integer> q;
24+
private Long sum;
25+
private int max;
2226

23-
/**
24-
* Initialize your data structure here.
25-
*/
26-
public MovingAverage(int size) {
27-
q = new LinkedList();
28-
sum = 0L;
29-
max = size;
30-
}
27+
/**
28+
* Initialize your data structure here.
29+
*/
30+
public MovingAverage(int size) {
31+
q = new LinkedList();
32+
sum = 0L;
33+
max = size;
34+
}
3135

32-
public double next(int val) {
33-
if (q.size() < max) {
34-
q.offer(val);
35-
sum += val;
36-
return (double) sum / q.size();
37-
} else {
38-
int first = q.poll();
39-
sum -= first;
40-
q.offer(val);
41-
sum += val;
42-
return (double) sum / q.size();
36+
public double next(int val) {
37+
if (q.size() < max) {
38+
q.offer(val);
39+
sum += val;
40+
return (double) sum / q.size();
41+
} else {
42+
int first = q.poll();
43+
sum -= first;
44+
q.offer(val);
45+
sum += val;
46+
return (double) sum / q.size();
47+
}
4348
}
4449
}
4550
}
46-
}
51+
}

0 commit comments

Comments
 (0)