題目:
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.
思路:
- 先算第一個框框總和
- 接下來只要把框框+後一個,-前一個,就可以得到一個新的總和
代碼:
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) {
// write your code here
if(nums.size()==0 || nums.size() < k || k == 0)
return {};
int currSum =0;
vector<int> ans;
for(int i =0; i<k; i++){
currSum+= nums[i];
}
ans.push_back(currSum);
for(int i=k; i<nums.size(); i++){
currSum+= nums[i];
currSum-= nums[i-k];
ans.push_back(currSum);
}
return ans;
}
};```