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,
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;
}
}
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;
}
}
相关文章推荐
- 51CTO学院三周年大庆之管家发福利
- springMVC 静态文件 访问
- JavaScript arguments对象
- Linux性能分析之mpstat&iostat&sar&vmstat
- 在 Java 词汇中没有“虚拟方法”一说
- java编码转换过程
- JS优秀插件收集
- Android OkHttp完全解析
- (第2讲)无序数组与有序数组的增删查
- CentOs下安装Crab
- IOCTL命令-_IO, _IOR, _IOW, _IOWR 幻数的理解
- 动态规划算法解最长公共子序列LCS问题
- Android系统截屏功能提取
- 第16周 阅读程序 4
- REST Datasnap服务端与javascript客户端实现
- 工信部电信投诉网站入口
- Android设计模式--Builder模式
- tomcat access log格式配置
- Poj 3311 Hie with the Pie【Floyd+状压dp】
- JS采用绝对定位实现回到顶部效果完整实例