给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的 连续 子数组,并返回其长度。如果不存在符合条件的子数组,返回 0。
示例: 输入:s = 7, nums = [2,3,1,2,4,3] 输出:2 解释:子数组 [4,3] 是该条件下的长度最小的子数组。
代码:
public class SubArrayLen {
public static int subArrayLen(int[] nums, int s) {
int result = Integer.MAX_VALUE;
int sum = 0;
// 滑动窗口起始位置
int index = 0;
// 子数组长度
int subLength = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
while (sum >= s) {
subLength = i - index + 1;
result = subLength < result ? subLength : result;
sum -= nums[index];
index++;
}
}
return result == Integer.MAX_VALUE ? 0 : result;
}
public static void main(String[] args) {
int[] nums = new int[]{2,3,1,2,4,3};
int s = 7;
System.out.println(subArrayLen(nums, s));
}
}