美文网首页工作生活
346-数据流中的移动平均值

346-数据流中的移动平均值

作者: 饮酒醉回忆 | 来源:发表于2019-07-03 10:53 被阅读0次

数据流中的移动平均值

题目

给定一个整数数据流和一个窗口大小,根据该滑动窗口的大小,计算其所有整数的移动平均值。

示例:

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();
    }
}

相关文章

网友评论

    本文标题:346-数据流中的移动平均值

    本文链接:https://www.haomeiwen.com/subject/zhxqhctx.html