class Solution {
public int minSubArrayLen(int target, int[] nums) {
int MAX = 100001;
int left = 0;
int right = 0;
int sum = nums[0];// 滑动窗口中的总和
int ans = MAX;// 符合条件的最小长度
while (right < nums.length) {
if (sum >= target) {
ans = (right - left + 1 < ans) ? (right - left + 1) : ans;
sum -= nums[left++];
} else {
if ((right + 1) >= nums.length) {
break;
}
sum += nums[++right];
}
}
if (ans == MAX) {
return 0;
} else {
return ans;
}
}
}
class Solution {
// 滑动窗口
public int minSubArrayLen(int s, int[] nums) {
int left = 0;
int sum = 0;
int result = Integer.MAX_VALUE;
for (int right = 0; right < nums.length; right++) {
sum += nums[right];
while (sum >= s) {
result = Math.min(result, right - left + 1);
sum -= nums[left++];
}
}
return result == Integer.MAX_VALUE ? 0 : result;
}
}
官方代码是遍历right指针,我觉得和我写的不分伯仲
right指针向后移动之后,sum再+
left指针移动之前,sum就-
不断的调节子序列的起始位置和终止位置