LeetCode 长度最小的子数组 JavaScript版本
给定一个含有 n 个正整数的数组和一个正整数 target 。
找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, …, numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
AC代码:
const MAX_Length = 90000000000;
var minSubArrayLen = function (target, nums) {
let p1 = 0, p2 = 0;
let minLength = MAX_Length;
while (p2 < nums.length) {
if (p1 == p2) {
if (nums[p1] >= target) {
minLength = 1;
}
p2++;
continue;
}
let sum = 0;
for (let i = p1; i <= p2; i++) {
sum += nums[i];
}
if (sum >= target) {
let length = p2 - p1 + 1;
if (length < minLength) {
minLength = length;
}
p1++;
} else {
p2++;
}
}
if (minLength == MAX_Length) {
return 0;
} else {
return minLength;
}
};
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/minimum-size-subarray-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。