Star

Leetcode 346. Moving Average from Data Stream

Question

Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.

For example,

1
2
3
4
5
MovingAverage m = new MovingAverage(3);
m.next(1) = 1
m.next(10) = (1 + 10) / 2
m.next(3) = (1 + 10 + 3) / 3
m.next(5) = (10 + 3 + 5) / 3

Explanation:

非常简单的题目,可以用queue或者arraylist或者array保存next的值。用一个sum存着总和,每次都计算一下平均值。

Code:

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
public class MovingAverage {
/** Initialize your data structure here. */
Queue<Integer> q = new LinkedList<>();
int size;
int count = 0;
int total = 0;
public MovingAverage(int size) {
this.size = size;
}
public double next(int val) {
if (count < size) {
count ++;
q.offer(val);
total += val;
return total*1.0 / count;
} else {
int remove = q.poll();
q.offer(val);
total -= remove;
total += val;
return total*1.0/ size;
}
}
}