class MovingAverage:
def __init__(self, size: int):
"""
Initialize your data structure here.
"""
self.size=size+1
self.front=0
self.rear=0
self.queue=[None for _ in range(size+1)]
self.sum=0
def next(self, val: int) -> float:
# 满了
if (self.rear+1)%self.size==self.front:
self.front=(self.front+1)%self.size
self.sum-=self.queue[self.front]
self.rear=(self.rear+1)%self.size
self.queue[self.rear]=val
self.sum+=val
return 1.0*self.sum/(self.size-1)
else:
self.rear=self.rear+1
self.queue[self.rear]=val
self.sum+=val
return 1.0*self.sum/(self.rear-self.front)
# Your MovingAverage object will be instantiated and called as such:
# obj = MovingAverage(size)
# param_1 = obj.next(val)
LEETCODE LCR 041. 数据流中的移动平均值
最新推荐文章于 2024-08-21 10:11:50 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)