LeetCode-209. 长度最小的子数组
难度:中等
给定一个含有 n 个正整数的数组和一个正整数 target 。
找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, …, numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int begin=0; //滑动窗口起始位置
int end; //滑动窗口终止位置
int sum = 0; //滑动窗口数值之和
int res = INT_MAX; //滑动窗口最小长度
for(int i=0;i<nums.size();i++){
sum += nums[i];
end = i;
while(sum >= target){
res = res < end-begin+1? res : end-begin+1 ;
if(sum - nums[begin] >= target){
sum = sum - nums[begin];
begin++;
res = res < end-begin+1? res : end-begin+1 ;
}
else{
break;
}
}
}
return res < INT_MAX ? res : 0;
}
};
执行结果:
通过
执行用时:
8 ms, 在所有 C++ 提交中击败了71.22%的用户
内存消耗:
10.3 MB, 在所有 C++ 提交中击败了33.92%的用户
通过测试用例:
19 / 19