题目 :和大于等于target的最短子数组
给定一个含有 n 个正整数的数组和一个正整数 target 。找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, …, numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
提示:
1 <= target <= 109
1 <= nums.length <= 105
1 <= nums[i] <= 105
解题
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int n = nums.length;
int ans = Integer.MAX_VALUE;
int l = 0;
int r = 0;
int sum = 0;
while (r < n) {
sum += nums[r];
while (sum >= target) {
ans = Math.min(ans,r - l + 1);//返回长度
if (ans == 1) {
return ans;
}
sum -= nums[l++];
}
r++;
}
return ans == Integer.MAX_VALUE ? 0 : ans;
}
}