LeetCode LCR 041. 数据流中的移动平均值

题目描述

LCR 041. 数据流中的移动平均值

思路分析

解法一:滑动窗口 + 队列(推荐)

核心思路

  • 用队列保存最近 size 个元素,同时维护窗口和 sum
  • 每次 next 先入队并累加,若长度超出则出队并减去。
  • 平均值为 sum / 当前窗口大小

复杂度分析

  • 时间复杂度:O(1),每次操作仅常数次入队出队。
  • 空间复杂度:O(size),窗口容量上限为 size
import java.util.*;

class MovingAverage {
    private final int size;
    private final Deque<Integer> queue;
    private long sum;

    public MovingAverage(int size) {
        this.size = size;
        this.queue = new ArrayDeque<>();
        this.sum = 0L;
    }

    public double next(int val) {
        queue.offerLast(val);
        sum += val;

        if (queue.size() > size) {
            sum -= queue.pollFirst();
        }

        return sum * 1.0 / queue.size();
    }
}
type MovingAverage struct {
    size  int
    sum   int
    queue []int
}

func Constructor(size int) MovingAverage {
    return MovingAverage{size: size}
}

func (m *MovingAverage) Next(val int) float64 {
    m.queue = append(m.queue, val)
    m.sum += val

    if len(m.queue) > m.size {
        m.sum -= m.queue[0]
        m.queue = m.queue[1:]
    }

    return float64(m.sum) / float64(len(m.queue))
}

相似题目

题目 难度 考察点
643. 子数组最大平均数 I 简单 滑动窗口
209. 长度最小的子数组 中等 滑动窗口
933. 最近的请求次数 简单 队列
239. 滑动窗口最大值 困难 单调队列
1429. 第一个唯一数字 中等 设计队列
本文作者:
本文链接: https://hgnulb.github.io/blog/2026/81678186
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!