题目(LeetCode #346)
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
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
|
题解
可使用固定大小的队列实现滑动窗口
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
| import java.util.Queue; import java.util.ArrayDeque;
class MovingAverage { private int maxSize; private double previousSum; private Queue<Integer> data;
public MovingAverage(int maxSize) { this.maxSize = maxSize; data = new ArrayDeque<>(); }
public double next(int val) { if (data.size() == maxSize) previousSum -= data.poll();
data.add(val); previousSum += val;
return previousSum / data.size(); } }
class Solution { public static void main(String[] args) { MovingAverage m = new MovingAverage(3); System.out.println(m.next(1)); System.out.println(m.next(10)); System.out.println(m.next(3)); System.out.println(m.next(5)); } }
|