码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 346. Moving Average from Data Stream

时间:2017-01-31 13:44:59      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:data   span   next   sum   from   构造   etc   win   structure   

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

标签:data   span   next   sum   from   构造   etc   win   structure   

原文地址:http://www.cnblogs.com/lettuan/p/6358750.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!