思路:双指针
-
start和end指向0
-
end后移,记录此时start到end的和:
如果小于target,则end接着后移,直到大于等于target;
如果大于等于target,start可以开始尝试后移,此时的和减去nums[start],直到和小于target,记录此时的最小长度
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
start=end=0
n=len(nums)
ans=n+1
total=0
while end<n:
total+=nums[end]
while total>=target:#start后移
ans=min(ans,end-start+1)
total-=nums[start]
start += 1
end+=1
return 0 if ans==n+1 else ans
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int len=nums.length;
int res=len+1;
int l=0,r=0;
int sum=0;
while(r<len){
sum+=nums[r];
while (sum>=target){
res=Math.min(res,r-l+1);
sum-=nums[l];
l++;
}
r++;
}
if (res==len+1){
res=0;
}
return res;
}
}