首页 > 代码库 > Leetcode 346. Moving Average from Data Stream
Leetcode 346. Moving Average from Data Stream
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
For example,
MovingAverage m = new MovingAverage(3); m.next(1) = 1 m.next(10) = (1 + 10) / 2 m.next(3) = (1 + 10 + 3) / 3 m.next(5) = (10 + 3 + 5) / 3
思路:本题比较简单,在__init__的时候,先构造一个stack = []。然后逐个往里面push元素,如果长度达到window size了,需要先pop最上面的一个元素。
1 class MovingAverage(object): 2 3 def __init__(self, size): 4 """ 5 Initialize your data structure here. 6 :type size: int 7 """ 8 self.win_size = size 9 self.stack = [] 10 11 12 def next(self, val): 13 """ 14 :type val: int 15 :rtype: float 16 """ 17 if len(self.stack) < self.win_size: 18 self.stack.append(float(val)) 19 return sum(self.stack)/len(self.stack) 20 else: 21 self.stack.pop(0) 22 self.stack.append(float(val)) 23 return float(sum(self.stack)/len(self.stack))
Leetcode 346. Moving Average from Data Stream
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。