携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第12天,点击查看活动详情
题目描述
给定一个整数数据流和一个窗口大小,根据该滑动窗口的大小,计算滑动窗口里所有数字的平均值。
实现 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
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/qIsx9U
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路分析
- 今天的算法题目是滑动窗口题目,作为一个设计类题目,我们需要选择合适的数据结构完成题目要求。题目具体的要求,滑动窗口的长度是 size, 求出滑动窗口的平均值。
- 求平均值,我们可以使用临时变量记录当前窗口的和。我们可以使用队列这种数据结构,作为滑动窗口的载体。队列(queue)是一种具有「先进入队列的元素一定先出队列」性质的表。由于该性质,队列通常也被称为先进先出(first in first out)表,简称 FIFO 表。queue 中 poll 方法可以快速从队列首部弹出一个元素。除了基本队列,还有双端队列数据结构,方便对队列中元素的进出操作。具体实现代码如下,供参考。
通过代码
class MovingAverage {
int maxSize;
double tempSum;
Queue<Integer> queue;
/** Initialize your data structure here. */
public MovingAverage(int size) {
this.maxSize = size;
this.queue = new LinkedList<>();
this.tempSum = 0.0;
}
public double next(int val) {
if (this.queue.size() == this.maxSize) {
int first = this.queue.poll();
this.tempSum -= first;
}
this.tempSum += val;
this.queue.offer(val);
return tempSum / this.queue.size();
}
}
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/
总结
- 今天的的这个题目比较简单,滑动窗口的时候,求解的是平均值。还有一类题目是求解滑动窗口的最值,需要我们使用具有排序属性的数据结构,比如堆来快速求解,解体思路也应该清楚。
- 坚持算法每日一题,加油!