给定一个含有 n 个正整数的数组和一个正整数 target 。
找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, …, numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
示例 1:
输入:target = 7, nums = [2,3,1,2,4,3]
输出:2
解释:子数组 [4,3] 是该条件下的长度最小的子数组。
示例 2:
输入:target = 4, nums = [1,4,4]
输出:1
示例 3:
输入:target = 11, nums = [1,1,1,1,1,1,1,1]
输出:0
思路
所谓滑动窗口,就是不断的调节子序列的起始位置和终止位置,从而得出我们要想的结果。
代码
暴力写法
class Solution {
public int minSubArrayLen(int target, int[] nums) {
// 暴力写法
// 最终结果
int result = Integer.MAX_VALUE;
// 子序列的长度
int res = 0;
// 子数组的和
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum = 0;
for (int j = i; j < nums.length; j++) {
sum += nums[j];
if (sum >= target) {
res = j - i + 1;
result = result < res? result : res;
break;
}
}
}
// 如果数组之和都没有大于或等于目标值,则返回 0
return result == Integer.MAX_VALUE? 0: result;
}
}
滑动窗口
class Solution {
public int minSubArrayLen(int target, int[] nums) {
// 移动窗口
int left = 0; // 初始指针(左指针)
int sum = 0; // 数组之和
int result = Integer.MAX_VALUE; // 最终返回结果
// 右指针遍历数组
for (int right = 0; right < nums.length; right++) {
// 子数组累加和
sum += nums[right];
// 存在符合条件的子数组
while(sum >= target) {
// 取最小子数组长度
result = result < right - left + 1 ? result : right - left + 1;
// 关键代码,在满足条件的情况下,缩小子数组最左边,判断是否还满足条件
sum -= nums[left++];
}
}
// 如果不存在符合条件的子数组,返回 0
return result == Integer.MAX_VALUE ? 0: result;
}
}