给定一个含有 n 个正整数的数组和一个正整数 target 。
找出该数组中满足其和 ≥ target 的长度最小的 连续子数组,并返回其长度。如果不存在符合条件的子数组,返回 0 。
标签:数组、双指针
/**双指针法
* 核心,两个指针start 、end,以end指针为循环,指针到达末尾为结束循环;
* 每次 判断总和与目标大小,不超过则start前进,并记录对应长度
* @param target
* @param nums
* @return
*/
public static int getMin(int target, int[] nums){
int start = 0,end ;
int sum = 0;
int result = Integer.MAX_VALUE;
int subLength;
for ( end = 0; end < nums.length; end++) {
sum += nums[end];
while (sum >= target){
subLength = end - start + 1;
result = result > subLength ? subLength : result;
sum -= nums[start++];
}
}
return result == Integer.MAX_VALUE ? 0 : result;
}
注意: 最后返回的结果与最大值比较一下(最初赋予了最大值),防止出现数组之和都不大于target的情况!