本文主要是介绍346. Moving Average from Data Stream,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
https://leetcode.com/problems/moving-average-from-data-stream/description/
题目大意:初始化一个滑动窗口,大小为w,输入一系列数,求窗口内的平均数,窗口会向前滑动,当窗口填满时,将最早进入的数弹出,加入新的数.
解题思路:用队列,求和时可以利用上次的和,不用每次从头到尾求
代码:
class MovingAverage {
public:/** Initialize your data structure here. */MovingAverage(int size) {q_size = size;sum = 0;}double next(int val) {double res;if (q.size() < q_size) { //当队列未达上限q.push(val);sum += val; //利用上次求和结果} else { //当队列达上限//减头sum -= q.front(); q.pop();//加尾q.push(val);sum += val; }res = (double)sum / q.size();return res;}
private:queue<int> q; //队列.模拟滑动窗口int q_size; //队列上限int sum; //暂存求和
};/*** Your MovingAverage object will be instantiated and called as such:* MovingAverage obj = new MovingAverage(size);* double param_1 = obj.next(val);*/
这篇关于346. Moving Average from Data Stream的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!