美文网首页
队列| Leetcode 346

队列| Leetcode 346

作者: 三更冷 | 来源:发表于2023-03-17 18:50 被阅读0次

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

    1、题目

    Leetcode 346. Moving Average from Data Stream

    • 实现 MovingAverage 类:

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

    相关文章

      网友评论

          本文标题:队列| Leetcode 346

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