KK's blog

每天积累多一些

0%

LeetCode 346 Moving Average from Data Stream

LeetCode



Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.

Implement the MovingAverage class:

MovingAverage(int size) Initializes the object with the size of the window size. double next(int val) Returns the moving average of the last size values of the stream.

Example 1:

Input
[“MovingAverage”, “next”, “next”, “next”, “next”]
[[3], [1], [10], [3], [5]]
Output
[null, 1.0, 5.5, 4.66667, 6.0]

Explanation
MovingAverage movingAverage = new MovingAverage(3);
movingAverage.next(1); // return 1.0 = 1 / 1
movingAverage.next(10); // return 5.5 = (1 + 10) / 2
movingAverage.next(3); // return 4.66667 = (1 + 10 + 3) / 3
movingAverage.next(5); // return 6.0 = (10 + 3 + 5) / 3


Constraints:

1 <= size <= 1000 -10<sup>5</sup> <= val <= 10<sup>5</sup>
* At most 10<sup>4</sup> calls will be made to next.

题目大意:

求data stream特定窗口的平均数

解题思路:

结构上跟LRU cache类似

解题步骤:

N/A

注意事项:

  1. 用queue

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def __init__(self, size: int):
self.queue = collections.deque()
self.size = size
self.sum = 0

def next(self, val: int) -> float:
if len(self.queue) < self.size:
self.queue.append(val)
self.sum += val
else:
n = self.queue.popleft()
self.sum -= n
self.queue.append(val)
self.sum += val
return self.sum / len(self.queue)

算法分析:

next时间复杂度为O(1),空间复杂度O(n)

Free mock interview