算法练习(16) - 数据流中的移动平均值

2022-06-15 16:09:00 浏览数 (1)

题目

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

示例:

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

题解

代码语言:javascript复制
import java.util.LinkedList;

public class MovingAverage {

    Integer window;

    Integer sum = 0;

    LinkedList<Integer> list = new LinkedList<>();

    public MovingAverage(Integer window){
        this.window = window;
    }
    public double next(Integer next) {
        list.offer(next);
        sum  =next;
        if(list.size() > window){
            Integer pop = list.pop();
            sum= sum - pop;
        }
        return sum / (double) list.size();
    }

    public static void main(String[] args) {
        MovingAverage movingAverage = new MovingAverage(3);

        System.out.println(movingAverage.next(1));
        System.out.println(movingAverage.next(10));
        System.out.println(movingAverage.next(3));
        System.out.println(movingAverage.next(5));
    }
}

输出

1.0 5.5 4.666666666666667 6.0

Process finished with exit code 0

0 人点赞