题目:209. 长度最小的子数组
解题思路:
- 初始化最小长度,设置为最大值,当最小长度变小时,该值更新
- 设置left和right指针,left指针用于记录左边界,当求和sum大于target时,左指针右移;right指针记录右边界,当求和sum小于target时,右指针右移,继续寻找符合要求的子字符串。
- 当右边界符合题目要求时,更新最小长度minLength
C代码实现
int minSubArrayLen(int target, int* nums, int numsSize){
int left = 0, right = 0;
//初始化最小长度为INT_MAX,最小值初始化为最大,最大值初始化为最小
int minLength = INT_MAX;
int sum = 0;
//右边界向右扩展
for(; right < numsSize; ++right) {
sum += nums[right];
//当sum的值大于等于target时,保存长度,并且收缩左边界
while(sum >= target) {
int subLength = right - left + 1;
minLength = minLength < subLength ? minLength : subLength;
sum -= nums[left++];
}
}
//判断最小长度是否为空,若为空,则返回0,否则返回minLength
return minLength == INT_MAX ? 0 : minLength;
}
Java代码实现
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int res = Integer.MAX_VALUE;
int left = 0;
int right = 0;
int temp = 0;
// 只管右指针,左指针的控制隐含在while(temp>=target)中,如果该条件不满足,则不用移动左指针
while(right < nums.length){
temp += nums[right];
while(temp >= target) {
res = Math.min(res, right - left + 1);
temp -= nums[left];
left++;
}
right++;
}
return res==Integer.MAX_VALUE ? 0 : res;
}
}