队列| Leetcode 346

2023-03-17  本文已影响0人  三更冷

Leetcode 分类刷题 —— 队列(Queue)

1、题目

Leetcode 346. Moving Average from Data Stream

MovingAverage(int size) 用窗口大小 size 初始化对象。
double next(int val) 成员函数 next 每次调用的时候都会往滑动窗口增加一个整数,请计算并返回数据流中最后 size 个值的移动平均值,即滑动窗口里所有数字的平均值。

2、思路

使用一个固定大小的队列来表示窗口,每次插入数据前判断队列是否已满,满了就删除队列的头元素,再在队列的尾部插入元素。
为避免频繁求和,使用一个sum变量保存队列里面元素的和。

3、Java 代码

class MovingAverage {
    
    private Queue<Integer> window = new ArrayDeque<>();
    private int maxSize;
    private double sum = 0.0;
 
    /** Initialize your data structure here. */
    public MovingAverage(int size) {
        this.maxSize = size;
    }
    
    public double next(int val) {
        if (this.window.size() == this.maxSize) {
            this.sum -= this.window.poll();
        }    
        
        this.sum += val;
        this.window.offer(val);
        return this.sum / this.window.size();
    }
 }
上一篇 下一篇

猜你喜欢

热点阅读