美文网首页
LintCode 604. Window Sum

LintCode 604. Window Sum

作者: aammyytt | 来源:发表于2018-04-15 11:16 被阅读0次

題目:
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.

思路:

  1. 先算第一個框框總和
  2. 接下來只要把框框+後一個,-前一個,就可以得到一個新的總和

代碼:

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;
       
    }
};```

相关文章

网友评论

      本文标题:LintCode 604. Window Sum

      本文链接:https://www.haomeiwen.com/subject/unrdkftx.html