链接:https://leetcode.com/problems/moving-average-from-data-stream/
题解:九章算法 - 帮助更多程序员找到好工作,硅谷顶尖IT企业工程师实时在线授课为你传授面试技巧
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
思路:一个队列就可以搞定,如果队列长度大于给定的窗口大小就将队首元素出队列.然后返回当前平均数即可.还有就是类成员初始化的时候要在初始化列表中进行,尽量不要在构造函数体中,内置的简单数据类型效率差不多.但是如果类成员是一个对象,在构造函数体中做赋值操作之前,这个类成员本身已经调用了自身的默认构造函数完成初始化了,也就是说在函数题中只是进行赋值操作.而在成员初始化列表中就不会再调用其默认构造函数了.
class MovingAverage {
public:
/** Initialize your data structure here. */
MovingAverage(int size): len(size), sum(0) {
}
double next(int val) {
sum += val;
que.push(val);
if(que.size() > len)
{
sum -= que.front();
que.pop();
}
return sum/que.size();
}
private:
int len;
double sum;
queue<int> que;
};
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/