346. Moving Average from Data St
2017-08-24 本文已影响0人
Jeanz
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
一刷
题解:首先要思考需要些什么变量
一个收尾相连的长度为size的数组,一个指向被替代位置的int, 一个当前数组含有多少个元素的int
class MovingAverage {
int[] window;
int insert, n;
long sum;
/** Initialize your data structure here. */
public MovingAverage(int size) {
window = new int[size];
insert = 0;
n = 0;
}
public double next(int val) {
if(n<window.length){
window[n++] = val;
sum+=val;
}else{
sum -= window[insert];
sum += val;
window[insert] = val;
insert++;
insert = insert%window.length;
}
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);
*/