给定一个含有?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
提示:
1 <= target <= 109
1 <= nums.length <= 105
1 <= nums[i] <= 105
力扣题解:. - 力扣(LeetCode)
方法1:时间超时(通过15/18)
public int minSubArrayLen(int target, int[] nums) {
int min = nums.length + 1;
for (int i = 0; i < nums.length; i++) {
int sum = 0;
int left = i;
sum += nums[left];
int right = i + 1;
while (right < nums.length && sum < target){
sum += nums[right];
right++;
}
if (sum >= target && min > right - left){
min = right - left;
}
}
return min == nums.length + 1? 0 : min;
}
方法2:(0ms)
public int minSubArrayLen(int target, int[] nums) {
int l = 0, r = 0;
int n = nums.length;
int sum = 0;
while(r < n && sum < target)
sum += nums[r++];
if(r == n)
if (sum < target)
return 0;
else{
while(sum > target)
sum -= nums[l++];
}
while(r < n){
if(sum < target) sum += nums[r++];
sum -= nums[l++];
}
if(sum < target) return r-l+1;
return r -l;
}
方法3:
public int minSubArrayLen(int target, int[] nums) {
int lo = 0, hi = 0, sum = 0, min = Integer.MAX_VALUE;
while (hi < nums.length) {
sum += nums[hi++];
while (sum >= target) {
min = Math.min(min, hi - lo);
sum -= nums[lo++];
}
}
return min == Integer.MAX_VALUE ? 0 : min;
}
?方法4:(2ms)
public int minSubArrayLen(int target, int[] nums) {
int left = 0;
int res = Integer.MAX_VALUE;
int add = 0;
for (int right = 0; right < nums.length; right++) {
add += nums[right];
while (add >= target) {
res = Math.min(res, right - left + 1);
add -= nums[left];
++left;
}
}
return res > nums.length ? 0 : res;
}