题目
链接:https://leetcode.cn/problems/2VG8Kg
给定一个含有 n 个正整数的数组和一个正整数 target 。
找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, …, numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
思路
滑动窗口法,用两个指针,都从最左边出发。
左指针不动,右指针向右。直到加和大于target,记录长度。
之后右指针不动,左指针向右,并将加和移除掉最左边的元素,直到加和小于target,记录长度。
之后左指针不动,右指针向右……如此往复。
解法:滑动窗口法
代码
public int minSubArrayLen(int target, int[] nums) {
int leftIndex = 0;
int rightIndex = 0;
int sum = 0;
int result = Integer.MAX_VALUE;
// 左指针不动,右指针向右
while (rightIndex < nums.length) {
sum += nums[rightIndex];
if (sum >= target) {
int length = rightIndex - leftIndex + 1;
result = Math.min(result, length);
leftIndex++;
// 右指针不动,左指针向右
while (leftIndex <= rightIndex) {
sum -= nums[leftIndex - 1];
if (sum < target) {
break;
}
length = rightIndex - leftIndex + 1;
result = Math.min(result, length);
leftIndex++;
}
}
rightIndex++;
}
return result == Integer.MAX_VALUE ? 0 : result;
}