LCR 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
次
思路
模拟滑动窗口即可(需要注意最开始一轮计算个数)
代码
模拟滑动窗口即可(需要注意最开始一轮计算个数)
public class MovingAverage {
private final int[] nums;
private double sum;
private int size;
private int index;
public MovingAverage(int size) {
this.nums = new int[size];
this.sum = 0;
this.size = 0;
this.index = 0;
}
public double next(int val) {
if (size < nums.length) {
size++; // 窗口未满,增加元素数量
} else {
sum -= nums[index]; // 窗口已满,移除最旧元素
}
sum += val; // 添加新元素
nums[index] = val; // 存储新元素
index = (index + 1) % nums.length; // 循环更新索引
return sum / size;
}
}
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 孤寂灬无痕
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果