侧边栏壁纸
博主头像
buukle博主等级

布壳儿

  • 累计撰写 109 篇文章
  • 累计创建 17 个标签
  • 累计收到 9 条评论

目 录CONTENT

文章目录

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

administrator
2021-06-24 / 0 评论 / 0 点赞 / 207 阅读 / 1213 字

题目

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

示例:

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

0

评论区