# 209. Minimum Size Subarray Sum

## 刷题内容

• https://leetcode.com/problems/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.

Example:

Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.


## 解题方案

/**
* @param {number} s
* @param {number[]} nums
* @return {number}
*/
var minSubArrayLen = function(s, nums) {
var left = 0;
var right = -1; // right 的起始位置很重要，这里选择-1 [left, right]这个区间刚开始是没有值的
var tmpSum = 0;
var minLength;

// 循环停止的条件是左指针小于长度
while (left < nums.length - 1) {
if(tmpSum < s) {
// 这里要注意边界的处理，当右指针移动到最后一个元素的时候结束
if(right >= nums.length -1) {
return minLength || 0;
}
right ++;
// 这里tmpSum的计算也很巧妙，直接用累加的方式，节省计算量
tmpSum = tmpSum + nums[right]
} else {
var tmp = right - left + 1;
if(minLength) {
if(tmp < minLength) {
minLength = tmp;
}
} else {
minLength = tmp;
}
// 左边指针移动减少sum的值
tmpSum = tmpSum - nums[left];
left ++;
}
}
if(!minLength) {
return 0;
}
return minLength;
};