列表

详情


剑指 Offer II 041. 滑动窗口的平均值

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

实现 MovingAverage 类:

 

示例:

输入:
inputs = ["MovingAverage", "next", "next", "next", "next"]
inputs = [[3], [1], [10], [3], [5]]
输出:
[null, 1.0, 5.5, 4.66667, 6.0]

解释:
MovingAverage movingAverage = new MovingAverage(3);
movingAverage.next(1); // 返回 1.0 = 1 / 1
movingAverage.next(10); // 返回 5.5 = (1 + 10) / 2
movingAverage.next(3); // 返回 4.66667 = (1 + 10 + 3) / 3
movingAverage.next(5); // 返回 6.0 = (10 + 3 + 5) / 3

 

提示:

 

注意:本题与主站 346 题相同: https://leetcode.cn/problems/moving-average-from-data-stream/

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
class MovingAverage { public: /** Initialize your data structure here. */ MovingAverage(int size) { } double next(int val) { } }; /** * Your MovingAverage object will be instantiated and called as such: * MovingAverage* obj = new MovingAverage(size); * double param_1 = obj->next(val); */

python3 解法, 执行用时: 100 ms, 内存消耗: 18.3 MB, 提交时间: 2022-05-27 15:36:06

class MovingAverage:

    def __init__(self, size: int):
        """
        Initialize your data structure here.
        """
        self.nums = []
        self.size = size


    def next(self, val: int) -> float:
        self.nums.append(val)
        if len(self.nums) > self.size:
            self.nums = self.nums[1:]
        return sum(self.nums) / len(self.nums)



# Your MovingAverage object will be instantiated and called as such:
# obj = MovingAverage(size)
# param_1 = obj.next(val)

上一题