给定一个含有 n
个正整数的数组和一个正整数 target
。找出该数组中满足其总和大于等于 target
的长度最小的 子数组 [numsl, numsl+1, ..., numsr-1, numsr]
,并返回其长度。如果不存在符合条件的子数组,返回 0
。
示例 1:
输入:target = 7, nums = [2,3,1,2,4,3] 输出:2 解释:子数组 [4,3] 是该条件下的长度最小的子数组。
示例 2:
输入:target = 4, nums = [1,4,4] 输出:1
示例 3:
输入:target = 11, nums = [1,1,1,1,1,1,1,1] 输出:0
提示:
1 <= target <= 109
1 <= nums.length <= 105
1 <= nums[i] <= 104
这题双重循环暴力解会超时。
学习了滑动窗口法。滑动窗口法本质是双指针法,定义前后两个指针表示窗口的前后边沿,因为指针始终后移,不会前移,因此时间复杂度O(n).核心代码如下
int minSubArrayLen(int target, vector<int>& nums) {//滑动窗口法O(n)
int n=nums.size();
int countmin=INT32_MAX;
int count=0,sum=0;
int i=0,j;//i,j分别为前后指针,即滑动窗口的前后边沿
for(j=0;j<n;j++){//外层循环移动窗口后边沿以找到足够大的窗口
sum+=nums[j];
while(sum>=target){
count=j-i+1;//count为当前窗口大小
countmin=count<countmin?count:countmin;//取小的
sum-=nums[i++];//sum已经大于target窗口时,前沿后移看能否有更小窗口
}
}
if(countmin==INT32_MAX)return 0;//countmin未被赋值过时返回0表示没有符合的子数组
return countmin;
}