Leetcode 346. Moving Average from Data Stream
Posted lettuan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章
[leetcode]346. Moving Average from Data Stream滑动窗口平均值
LeetCode 346. Moving Average from Data Stream (数据流动中的移动平均值)
346. Moving Average from Data Stream - Easy
[LeetCode] 1033. Moving Stones Until Consecutive