滑动窗口法
从题目中提取信息,输入为数组,且长度固定为k,求所有子数组的平均数,则很显然是一个滑动窗口问题,用for循环来维持一个窗口的end,每次进来都加且减一个数,在没有到达窗口最大值时就一直加且累计此子数组的sum,当达到最大值后加一个数就减一个数且计算平均值赋值
public static double[] findAverages(int K, int[] arr) {
double[] result = new double[arr.length - K + 1];
double windowSum = 0;
int windowStart = 0;
for (int windowEnd = 0; windowEnd < arr.length; windowEnd++) {
windowSum += arr[windowEnd]; // add the next element
// slide the window, we don't need to slide if we've not hit the required window size of 'k'
if (windowEnd >= K - 1) {
result[windowStart] = windowSum / K; // calculate the average
windowSum -= arr[windowStart]; // subtract the element going out
windowStart++; // slide the window ahead
}
}
return result;
}