346. Moving Average from Data Stream
2018-03-07 08:01
295 查看
问题描述
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
题目链接:
思路分析
滑动窗口计算平均数,限定计算size个数的平均数。将每一次的输入保存在队列中,并保持一个sum来记录队列中元素和。如果队列中元素小于size,push进队后计算平均数,注意++n,因为元素个数增多了;如果到了size了,就先pop再push,sum做相同操作,再进行计算。
代码
class MovingAverage { public: /** Initialize your data structure here. */ queue<int> window; double sum = 0; int cap; MovingAverage(int size) { cap = size; } double next(int val) { int n = window.size(); if (n < cap){ sum = sum + val; window.push(val); return sum/(++n); } else{ sum = sum - window.front() + val; window.pop(); window.push(val); return sum/cap; } } }; /** * Your MovingAverage object will be instantiated and called as such: * MovingAverage obj = new MovingAverage(size); * double param_1 = obj.next(val); */
时间复杂度:O(1)
空间复杂度:O(n)
反思
对于队列的使用。相关文章推荐
- 346. Moving Average from Data Stream
- Leetcode 346 Moving Average from Data Stream
- 346. Moving Average from Data Stream
- [leetcode] 346. Moving Average from Data Stream 解题报告
- 346. Moving Average from Data Stream
- Leetcode Everyday: 346. Moving Average from Data Stream
- [Leetcode] 346. Moving Average from Data Stream 解题报告
- [LeetCode] 346. Moving Average from Data Stream 从数据流中移动平均值
- Moving Average from Data Stream
- Moving Average from Data Stream
- LeetCode Moving Average from Data Stream
- Moving Average from Data Stream
- Moving Average from Data Stream
- Moving Average from Data Stream -- LeetCode
- Moving Average from Data Stream
- [LeetCode] Moving Average from Data Stream 从数据流中移动平均值
- Leetcode: Moving Average from Data Stream
- Moving Average from Data Stream
- 295. Find Median from Data Stream
- LeetCode295——Find Median from Data Stream