209.长度最小子数组
思路:滑动窗口
1.移动右边界,增大窗口,累加sum
2.如果一旦sum>target,移动左边界,缩小窗口,直到sum<target
复杂度:
时间:O(n)
空间:O(1)
代码:
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int i=0;
int j=0;
int minLength=INT_MAX;
int sum=0;
while(j<nums.size()){
sum=sum+nums[j];
while(sum>=target){
minLength=min(minLength,j-i+1);
sum=sum-nums[i];
i++;
}
j++;
}
return minLength==INT_MAX?0:minLength;
}
};