您的位置:首页 > 其它

Leetcode 346 Moving Average from Data Stream

2017-01-10 06:54 295 查看
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

首先这是一个Window的问题,要注意window满了之后每次都会替换最老的那一个元素

public class MovingAverage {

private int[] window;
private int insert,n;
private long sum;

/** Initialize your data structure here. */
public MovingAverage(int size) {
window = new int[size];
insert = 0;//insert代表的就是下一个要被替换的元素的位置
sum = 0;
}

public double next(int val) {
if (n < window.length) n++;
sum -= window[insert];
sum += val;
window[insert] = val;
insert = (insert + 1) % window.length;//insert的数值变化分别为0,1,2,0,1,2.。。。。

return (double)sum / n;

}
}

/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/

不一定就要让window进行移动,可以按照012012012.。。的顺序进行替换
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: