administrator
Published on 2021-06-24 / 207 Visits
0
0

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

题目

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

示例:

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

题解

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


Comment