Lintcode 604. Sum of numbers in sliding window
Title description:
Give you an integer array of size n and a sliding window of size k, move the sliding window from the beginning to the end, and output the sum of the numbers in the sliding window at each moment from the beginning to the end.
class Solution {
public:
/**
* @param nums: a list of integers.
* @param k: length of window.
* @return: the sum of the element inside the window at each moving.
*/
vector<int> winSum(vector<int> &nums, int k) {
if (nums.size() < k || k <= 0) {
return vector<int>();
}
int n = nums.size();
vector<int> sums(n - k + 1, 0);
for (int i = 0; i < k; ++i) {
sums[0] += nums[i];//计算nums的前k数之和
}
for (int i = 1; i < n - k + 1; ++i) {
sums[i] = sums[i - 1] - nums[i - 1] + nums[i + k - 1];
}
return sums;
}
};