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
2、扩大窗口,此时和为5,仍小于目标7
3、继续扩大窗口,此时和为6,仍小于目标7
4、继续扩大窗口,此时和为8,大于目标7,满足要求,此时窗口大小为4
5、缩小窗口,此时和为6,小于目标7
6、扩大窗口,此时和为10,大于目标7,满足要求,此时窗口大小为4,目前最小的窗口为4
7、缩小窗口,此时和为7,等于目标7,满足要求,此时窗口大小为3,目前最小窗口为3
8、缩小窗口,此时和为6,小于目标7
9、扩大窗口,此时和为9,大于目标7,满足要求,此时窗口大小为3,目前最小窗口大小为3
10、缩小窗口,此时和为7,等于目标7,满足要求,此时窗口大小为2,目前最小窗口大小为2
11、缩小窗口,此时和为3,小于目标7,达到最后一个数,遍历结束
参照这个过程,我们可以得到代码:
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;
}
}