LintCode - Window Sum
阿新 • • 發佈:2018-11-19
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) { // write your code here int n = nums.size(); if(n<k || k==0) return {}; int sum = 0; for(int i=0;i<k;i++){ sum += nums[i]; } vector<int> res{sum}; int l=1, r=k; while(r<n){ sum = sum-nums[l-1]+nums[r]; res.push_back(sum); l++; r++; } return res; } };