力扣209.长度最小的数组
-
模版滑窗求最小
cpp
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int n = nums.size(),res=n+1;
int sum = 0;
for(int i=0,j=0;i<n;i++)
{
sum += nums[i];
//尽可能缩小区间
while(sum - nums[j] >= target)
{
sum -= nums[j++];
}
if(sum >= target) res = min(res,i-j+1);
}
if(res == n+1) return 0;
else return res;
}
};