Skip to content

Commit 674c36a

Browse files
committed
346
1 parent 1ebc2fa commit 674c36a

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,5 +62,6 @@ Success is like pregnancy, Everybody congratulates you but nobody knows how many
6262
| # | Title | Solution | Time | Space | Difficulty |Tag| Note|
6363
|-----|-------| -------- | ---- | ------|------------|---|-----|
6464
|155|[Min Stack](https://leetcode.com/problems/min-stack/#/description)| [Python](./stack_queue/minStack.py) | _O(1)_| _O(n)_ | Easy | ||
65-
|225|[Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/#/description)| [Python](./stack_queue/queueStack.py) | push/top/pop: _O(n)_| _O(n)_ | Easy | ||
65+
|225|[Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/#/description)| [Python](./stack_queue/queueStack.py) | push/pop: _O(1)_ top:_O(n)_ | _O(n)_ | Easy | ||
6666
|20|[Valid Parentheses](https://leetcode.com/problems/valid-parentheses/#/description)| [Python](./stack_queue/isValid.py) | _O(n)_| _O(n)_ | Easy | ||
67+
|346|[Moving Average from Data Stream](https://leetcode.com/problems/moving-average-from-data-stream/#/description)| [Python](./stack_queue/movingAverage.py) | _O(1)_| _O(n)_ | Easy | ||

stack_queue/movingAverage.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#!/usr/bin/python
2+
# -*- coding: utf-8 -*-
3+
4+
# Author: Yu Zhou
5+
6+
# ****************
7+
# Descrption:
8+
# 346. Moving Average from Data Stream
9+
10+
#Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
11+
# ****************
12+
13+
# 思路:
14+
# 没什么难度,基础的stack知识,当size超过self.size的时候,pop掉第一个进入queue的,再加上新的就行了
15+
# 若没超过size,就继续push
16+
17+
# ****************
18+
# Final Solution *
19+
# ****************
20+
class MovingAverage(object):
21+
def __init__(self, size):
22+
self.size = size
23+
self.queue = []
24+
25+
def next(self, val):
26+
if not self.queue or len(self.queue) < self.size:
27+
self.queue.append(val)
28+
else:
29+
self.queue.pop(0)
30+
self.queue.append(val)
31+
return float(sum(self.queue)) / len(self.queue)

0 commit comments

Comments
 (0)