您的位置:首页 > 其它

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)

反思

对于队列的使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: