题目
https://leetcode-cn.com/problems/minimum-size-subarray-sum/
思路
滑动窗口,首先向右扩大窗口,若此时窗口内的值大于target,那么可以收缩窗口,即是从左边压缩,找到最小值并记录
code
/**
* @param {number} target
* @param {number[]} nums
* @return {number}
*/
var minSubArrayLen = function(target, nums) {
return f(target, nums);
};
const f = function (target, nums){
let left = 0;
// let right = 0;
let min_len = Infinity;
let sum = 0;
for (let i=0; i<nums.length; i++){
sum += nums[i];
while (sum >= target){
let cur_len = i-left+1;
min_len = Math.min(cur_len, min_len);
sum -= nums[left];
left++;
}
}
return min_len == Infinity?0:min_len;
}