Lintcode 604. 滑动窗口内数的和
题目描述:
给你一个大小为n的整型数组和一个大小为k的滑动窗口,将滑动窗口从头移到尾,输出从开始到结束每一个时刻滑动窗口内的数的和。
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;
}
};