题目:给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的 连续 子数组,并返回其长度。如果不存在符合条件的子数组,返回 0。
分析题意:有一个正整数数组和正整数s,寻找数组中一个连续子数组其和要满足≥ s。
返回结果:连续子数组的长度,如果不存在则返回0;
数组如下:
- 如果s为100时候,肯定是找不到的。此时结果返回为0,
- 如果s为7时,首先找到连续子数组[2,3,1,2]->[3,1,2,4]->[1,2,4] ->[4,3]最终返回的结果为2(子数组长度)
过程如下:
参数:数组定义为
int[] nums = {2,3,1,2,4,3}; int target = 7;
// 左右指针用来控制滑动窗口长度
int left = 0;
// 记录窗口长度
int length = 0;
// 记录子数组结果
int result = nums.length + 1;
// 记录子数组之和
int sum = 0;
【外层循环】: for (int right = 0; right < nums.length; right++) {
【第一步】: sum+= nums[right]
【 内层循环】 循环条件:while(sum >= 7(target))
【第二步】:计算legth的长度 = right - left + 1;结果result = Math.(result,length)
【第三步】:因为sum >=7,因此要抛去left所对应的值,此时sum-=num[left],left++;
当外层循环结束后要返回结果集
return result == nums.length + 1 ? 0:result;
思考:为什么 要这样返回呢?
原因是:
- 考虑如下情况 nums = [1,1,1,1,1,1,1,1],target = 11; 以至于子数组和sum 永远小于target,此时【外层循环】结束。
- 说明我们没有找到一个子数组使得其和等于sum 应该返回 0;
可能会有人思考:为什么result的初始值 = num.length + 1呢?
因为:滑动窗口的长度length最大只能为数组长度,
所以在result与length中第一次比较时,length 永远小于result,这样就可以更新result的值了。
package array;
public class MinSubArrayLen {
public static void main(String[] args) {
int[] nums = {2,3,1,2,4,3};
int target = 7;
int result = minSubArrayLen(target, nums);
System.out.println(result);
}
public static int minSubArrayLen(int target, int[] nums) {
// 左右指针用来控制滑动窗口长度
int left = 0;
// 记录窗口长度
int length = 0;
// 记录子数组结果
int result = nums.length + 1;
// 记录子数组之和
int sum = 0;
for (int right = 0; right < nums.length; right++) {
sum += nums[right];
while (sum >= target) {
length = right - left + 1;
result = Math.min(result, length);
sum -= nums[left];
left++;
}
}
return result == nums.length + 1 ? 0:result;
}
}