desscription:
Given an array of n integer, and a moving window(size k), move the window at each iteration from the start of the array, find the sum of the element inside the window at each moving.
Have you met this question in a real interview? Yes
Example
For array [1,2,7,8,5], moving window size k = 3.
1 + 2 + 7 = 10
2 + 7 + 8 = 17
7 + 8 + 5 = 20
return [10,17,20]
解题思路:
首先建立出一个sum,例如k = 3,然后计算出前3个数的和。每当向后移动一位时,sum减掉前面的一个数然后加上后面的一个数。
public class Solution {
/**
* @param nums a list of integers.
* @return the sum of the element inside the window at each moving.
*/
public int[] winSum(int[] nums, int k) {
// write your code here
int[] arr = new int[nums.length - k + 1];
if (nums == null || nums.length == 0) {
return new int[] {};
}
int sum = 0;
for (int i = 0; i < k; i++) {
sum += nums[i];
}
arr[0] = sum;
for (int i = 1; i < nums.length - k + 1; i++) {
sum = sum - nums[i - 1] + nums[i + k - 1];
arr[i] = sum;
}
return arr;
}
}