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))