-
Notifications
You must be signed in to change notification settings - Fork 1
/
Question041.java
68 lines (61 loc) · 2.07 KB
/
Question041.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
package com.hncboy.swordreferstoofferspecial;
import java.util.LinkedList;
import java.util.Queue;
/**
* @author hncboy
* @date 2021/11/2 9:07
* @description 剑指 Offer II 041. 滑动窗口的平均值
*
* 给定一个整数数据流和一个窗口大小,根据该滑动窗口的大小,计算滑动窗口里所有数字的平均值。
*
* 实现 MovingAverage 类:
* MovingAverage(int size) 用窗口大小 size 初始化对象。
* double next(int val) 成员函数 next 每次调用的时候都会往滑动窗口增加一个整数,
* 请计算并返回数据流中最后 size 个值的移动平均值,即滑动窗口里所有数字的平均值。
*
*
* 示例:
* 输入:
* inputs = ["MovingAverage", "next", "next", "next", "next"]
* inputs = [[3], [1], [10], [3], [5]]
* 输出:
* [null, 1.0, 5.5, 4.66667, 6.0]
*
* 解释:
* MovingAverage movingAverage = new MovingAverage(3);
* movingAverage.next(1); // 返回 1.0 = 1 / 1
* movingAverage.next(10); // 返回 5.5 = (1 + 10) / 2
* movingAverage.next(3); // 返回 4.66667 = (1 + 10 + 3) / 3
* movingAverage.next(5); // 返回 6.0 = (10 + 3 + 5) / 3
*
* 提示:
* 1 <= size <= 1000
* -105 <= val <= 105
* 最多调用 next 方法 104 次
*
* 注意:本题与主站 346 题相同: https://leetcode-cn.com/problems/moving-average-from-data-stream/
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/qIsx9U
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class Question041 {
private static class MovingAverage {
private final int length;
private final Queue<Integer> queue;
private double sum;
public MovingAverage(int size) {
length = size;
queue = new LinkedList<>();
sum = 0;
}
public double next(int val) {
if (queue.size() == length) {
sum -= queue.remove();
}
queue.add(val);
sum += val;
return sum / queue.size();
}
}
}