Leetcode209:长度最小的子数组
-
题目:
-
给定一个含有 n 个正整数的数组和一个正整数 target 。
找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, …, numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
-
-
思路:滑动窗口
-
代码如下:
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int n = nums.length;
int sum = 0;
int res = Integer.MAX_VALUE;
int left = 0;
for(int right = 0; right < n; right++){
sum += nums[right];
while(sum>=target){
res = Math.min(res,right - left +1);
sum -= nums[left++];
}
}
return res == Integer.MAX_VALUE ? 0: res;
}
}