class Solution {
public:
int minSubArrayLen( int target, vector<int>& nums) {
int slowIndex = 0,fastIndex = 0;
int n = nums.size();
int length = INT_MAX;
int sum = 0;
for(int fastIndex = 0; fastIndex < n; ++fastIndex){
sum += nums[fastIndex];
while(sum >= target){
int nowLen = fastIndex - slowIndex + 1;
length = length > nowLen ? nowLen : length;
sum -= nums[slowIndex++];
}
}
return length == INT_MAX? 0 : length;
}
};
代码(二刷自解 2024年4月15日
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
// 双指针移动,右指针超过统计长度,右移左指针直到不满足条件
int left = 0, right = 0;
int sum = 0;
int res = INT_MAX;
while (right != nums.size()) {
// 当超过时移动左指针
sum += nums[right++];
while (sum >= target) {
res = min(right - left, res);//注意,这行必须放在移动左指针里面才能找到最小
sum = sum - nums[left];
left++;
}
}
return res == INT_MAX ? 0 : res;
}
};