给定长度的sliding window, 求出数字流在这个window区间的平均值:
解法:前缀和数组:
index : 1 2 3 4
d : 1 10 3 5
sum: 1 11 14 19
sum[i] = d[1] + d[2] + ... + d[i]
d[x] + d[x+1] + ... + d[y] = sum[y] - sum[x-1]
优化:使用滚动数组来优化空间复杂度。
对于滑动窗口为3时,只存4个,即可以将下标变为 index %= 4
0 1 2 3 4 5 6 7 8 9
0 1 2 3 0 1 2 3 0 1
小技巧:滚动数组越长越不容易出错,所以取 >= size+1 就都可以
class MovingAverage { public: /* * @param size: An integer */ vector<double> sum; int id, size; MovingAverage(int size): sum(size+1, 0) { //因为不知道sum数组的范围,故设一个大的值 // do intialization if necessary id = 0; this->size = size; //给成员变量size赋值 } int mod(int x){ return x % (size+1); } /* * @param val: An integer * @return: */ double next(int val) { // write your code here id++; sum[mod(id)] = sum[mod(id-1)] + val; //前缀和数组 //sum[0] = 0 为dummy node if(id - size >= 0){ return (sum[mod(id)] - sum[mod(id-size)]) / size; } else return sum[mod(id)] / id; } }; /** * Your MovingAverage object will be instantiated and called as such: * MovingAverage obj = new MovingAverage(size); * double param = obj.next(val); */