力扣 209 题 长度最小的数组
给定一个含有 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
起源:力扣(LeetCode)链接:https://leetcode.cn/problems/minimum-size-subarray-sum
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。
暴力解法
class Solution {public int minSubArrayLen(int target, int[] nums) {
int minLength = nums.length+1;
for(int left = 0;left < nums.length; left++){for(int right = left; right< nums.length; right++){
int sum = 0;
for(int i = left; i <= right; i++){sum += nums[i];
}
if(sum >= target){
int tmplength = right-left+1;
minLength = min(tmplength, minLength);
break;
}
}
}
if(minLength == nums.length+1){return 0;}
return minLength;
}
int min(int a, int b){return a < b? a:b;}
}
滑动窗口
class Solution {public int minSubArrayLen(int target, int[] nums) {
int minLength = nums.length +1;
int left = 0;
int sum = 0;
for(int right = 0; right < nums.length; right++){sum += nums[right];
while(sum >= target){
int l = right-left+1;
minLength = min(l, minLength);
sum -= nums[left++];
}
}
return minLength==nums.length +1? 0: minLength;
}
int min(int a, int b){return a < b? a:b;}
}