滑动窗口,用双指针实现:
- 窗口内之和小于目标值时右指针向右移动增加窗口宽度;
- 窗口内之和大于目标值时左指针向右移动减少窗口宽度。
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
if (nums.empty()) return 0;
int left = 0;
int curSum = 0;
int minLength = INT_MAX;
for (int right = 0; right < nums.size(); ++ right)
{
curSum += nums[right];
while (left <= right && curSum >= target)
{
minLength = min(minLength, right - left + 1);
curSum -= nums[left ++ ];
}
}
return minLength == INT_MAX ? 0 : minLength;
}
};