长度最小的子数组
给定一个含有 n
个正整数的数组和一个正整数 target
。
找出该数组中满足其总和大于等于 target
的长度最小的
子数组
[numsl, numsl+1, ..., numsr-1, numsr]
,并返回其长度**。**如果不存在符合条件的子数组,返回 0
。
public int minSubArrayLen(int target, int[] nums) {
int start = 0;
int end = 0;
int len = nums.length+1;
int sum = 0;
while(end < nums.length){
if(sum < target){
sum += nums[end];
}
while (sum >= target) {
len = Math.min(len,end-start+1);
sum -= nums[start];
start++;
}
end ++;
}
return len == nums.length+1 ? 0 : len;
}
双指针,右指针一点点右移直到总和大于target
此时左移左指针直到总和小于target