您的位置:首页 > 其它

LeetCode 346. Moving Average from Data Stream

2016-06-20 12:09 246 查看
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

This one is to use the Deque structure.

#include <queue>
#include <iostream>
using namespace std;

class MovingAverage {
private:
queue<int> q;
int size;
double sum;

public:
MovingAverage(int size) {
this->size = size;
sum = 0;
}

double next(int val) {
if(q.size() >= size) {
sum -= q.front();
q.pop();
}
q.push(val);
sum += val;
return double(sum)/q.size();
}
};

int main(void) {
MovingAverage a(3);
int tmp;
while(cin >> tmp) {
cout << "average: " << a.next(tmp) << endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: