1. 程式人生 > 其它 >【兩根指標——同向雙指標】Lintcode 604. 滑動視窗內數的和

【兩根指標——同向雙指標】Lintcode 604. 滑動視窗內數的和

技術標籤:刷題之路雙指標c++陣列

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