算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 数据流中的移动平均值,我们先来看题面:
https://leetcode-cn.com/problems/reverse-vowels-of-a-string/
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
给定一个整数数据流和一个窗口大小,根据该滑动窗口的大小,计算其所有整数的移动平均值。
示例
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
思路:一个队列记录数字,用一个变量记录窗口和即可,每次更新窗口和。
解题
内部实现使用一个队列来做,判断当前队列大小和限定大小,将总和加减,之后算平均数
public class MovingAverage {
private double previousSum = 0.0;
private int maxSize;
private Queue<Integer> currentWindow;
/** Initialize your data structure here. */
public MovingAverage(int size) {
currentWindow = new LinkedList<Integer>();
maxSize = size;
}
public double next(int val) {
if(currentWindow.size()==maxSize){
previousSum -= currentWindow.remove();
}
currentWindow.add(val);
previousSum += val;
return previousSum/currentWindow.size();
}
}
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文: