LintCode-604: Window Sum (滑动窗口经典题)

  1. Window Sum

Given an array of n integers, 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.

Example
Example 1

Input:array = [1,2,7,8,5], k = 3
Output:[10,17,20]
Explanation:
1 + 2 + 7 = 10
2 + 7 + 8 = 17
7 + 8 + 5 = 20

滑动窗口的经典题。
解法1:用deque。

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 winSum(vector &nums, int k) {
        deque dq;
        int sum = 0;
        vector result;
        for (int i = 0; i < nums.size(); ++i) {
            if (dq.size() < k) {
                dq.push_back(nums[i]);
                sum += nums[i];
                if (dq.size() == k) result.push_back(sum);
                continue;
            }
            
            dq.push_back(nums[i]);
            sum += nums[i] - dq.front();
            dq.pop_front();

            result.push_back(sum);
        }
        return result;
    }
};

解法2:啥都不用,直接用vector。网上的程序。效率很高。

   vector winSum(vector &nums, int k) {
        if (nums.size() < k || k <= 0)
            return vector();

        int n = nums.size();
        vector sums(n - k + 1, 0);

        for (int i = 0; i < k; i++)
            sums[0] += nums[i];
        for (int i = 1; i < n - k + 1; i++) {
            sums[i] = sums[i-1] - nums[i-1] + nums[i + k-1];
        }
        return sums;
    }

下面这个写法可能稍微清楚一点:

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 winSum(vector &nums, int k) {
        int n = nums.size();
        if (n == 0) return vector();
        vector result;
        int p1 = 0, p2 = 0;
        int sum = 0;
        
        while(p2 < n) {
        
            if (p2 - p1 < k) {
                sum += nums[p2];
                if (p2 - p1 == k - 1) result.push_back(sum);
            } else {
                sum += nums[p2] - nums[p1];
                p1++;
                result.push_back(sum);
            }
            p2++;
            
        }
        
        return result;
    }
};

另外,这里是每个sliding window的sum都必须记录,所以要用sums[]。但如果只是求所有sliding window的sum的最大值,只需要一个sum变量就够了。

代码同步在
https://github.com/luqian2017/Algorithm

你可能感兴趣的:(LintCode-604: Window Sum (滑动窗口经典题))