leetcode209:长度最小的子数组
1.题目描述
给定一个含有 n 个正整数的数组和一个正整数 target 。
找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
力扣链接:https://leetcode-cn.com/problems/minimum-size-subarray-sum
2.解题思路
a.暴力求解,在需要一个最大的数的时候可以使用最大整数Integer.MAX_VALUE,在寻找较小的数可以使用Math.min(minLength, j - i + 1)
3.代码
public static int minSubArrayLen(int target, int[] nums) {
int numsLength = nums.length;
if (numsLength == 1) {
if (target == nums[0]) {
return 1;
} else {
return 0;
}
}
// 维护一个大数据,使用最大的整数
int minLength = Integer.MAX_VALUE;
for (int i = 0; i < numsLength; i++) {
// 有一个数和目标数相同,直接返回1
if (nums[i] >= target) {
return 1;
} else {
int temValue = nums[i];
for (int j = i + 1; j < numsLength; j++) {
temValue = temValue + nums[j];
if (temValue >= target) {
//更新最小长度
minLength = Math.min(minLength, j - i + 1);
break;
}
}
}
}
// 判断是否为最初始的值,如果是返回0,不是则返回对应的长度
return minLength == Integer.MAX_VALUE ? 0 : minLength;
}

浙公网安备 33010602011771号