209. Minimum Size Subarray Sum

Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.

For example, given the array [2,3,1,2,4,3] and s = 7,
the subarray [4,3] has the minimal length under the problem constraint.

解析
  本题最直观的解法是用两个循环,但是显然很容易超时,所以需要考虑使用一种类似于“窗口”的解法:
1、窗口中的元素当前只有一个,和为2,小于目标7

209. Minimum Size Subarray Sum_第1张图片

2、扩大窗口,此时和为5,仍小于目标7

209. Minimum Size Subarray Sum_第2张图片

3、继续扩大窗口,此时和为6,仍小于目标7

209. Minimum Size Subarray Sum_第3张图片

4、继续扩大窗口,此时和为8,大于目标7,满足要求,此时窗口大小为4

209. Minimum Size Subarray Sum_第4张图片

5、缩小窗口,此时和为6,小于目标7

209. Minimum Size Subarray Sum_第5张图片

6、扩大窗口,此时和为10,大于目标7,满足要求,此时窗口大小为4,目前最小的窗口为4

209. Minimum Size Subarray Sum_第6张图片

7、缩小窗口,此时和为7,等于目标7,满足要求,此时窗口大小为3,目前最小窗口为3

209. Minimum Size Subarray Sum_第7张图片

8、缩小窗口,此时和为6,小于目标7

209. Minimum Size Subarray Sum_第8张图片

9、扩大窗口,此时和为9,大于目标7,满足要求,此时窗口大小为3,目前最小窗口大小为3

209. Minimum Size Subarray Sum_第9张图片

10、缩小窗口,此时和为7,等于目标7,满足要求,此时窗口大小为2,目前最小窗口大小为2

209. Minimum Size Subarray Sum_第10张图片

11、缩小窗口,此时和为3,小于目标7,达到最后一个数,遍历结束

209. Minimum Size Subarray Sum_第11张图片

参照这个过程,我们可以得到代码:

var minSubArrayLen = function (s, nums) {
    let numsLen = nums.length, minLen = Infinity;
    if (numsLen) {
        let start = 0, end = 0, curSum = 0;
        while (start < numsLen && end < numsLen) {
            while (curSum < s && end < numsLen) {
                curSum += nums[end++];
            }
            while (curSum >= s && end >= start) {
                minLen = Math.min(end - start, minLen);
                curSum -= nums[start++];
            }
        }
    }
    if (minLen === Infinity) {
        return 0;
    }
    else {
        return minLen;
    }
}

你可能感兴趣的:(209. Minimum Size Subarray Sum)