您的位置:首页 > 其它

[Leetcode] 346. Moving Average from Data Stream 解题报告

2017-08-11 16:05 579 查看
题目

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

思路

我们维护一个队列,并且保证这个队列中元素的个数不超过用户定义的窗口大小。为了将double next(int val)函数的时间复杂度从O(n)降低到O(1),我们额外维护一个当前队列元素的和sum。每次进入新元素的时候对sum进行更新。这样double next(int val)函数的时间复杂度就被降低为O(1)了,而该算法总的空间复杂度是O(n),其中n是构造函数中所定义的窗口大小。

代码

class MovingAverage {
public:
/** Initialize your data structure here. */
MovingAverage(int size) {
capacity = size;
sum = 0;
}

double next(int val) {
if (capacity == q.size()) {
int num = q.front();
q.pop();
sum -= num;
}
q.push(val);
sum += val;
double count = static_cast<double>(q.size());
return sum / count;
}
private:
queue<int> q;
int capacity;
long long sum; // in order to avoid overflow
};

/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: