Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn’t one, return 0 instead.
Example:
Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.
给出n个正数的数组和一个正数s,找出最小的连续子数组长度,使这段子数组的和>=s,如果不存在这样的子数组,返回0
思路:
因为要求子数组是连续的,先从左到右逐个加入元素,直到和>=s,然后再从左侧逐一减去元素,直到不再满足和>=s。然后右边界右移,重复这样的过程,直到右边界到达nums的长度。记录下这个过程中最小的长度
public int minSubArrayLen(int target, int[] nums) {
int n = nums.length;
int left = 0;
int right = 0;
int res = n+1;
int sum = 0;
while(right < n) {
while(right < n && sum < target) {
sum += nums[right];
right++;
}
while(sum >= target) {
res = Math.min(res, right-left);
sum -= nums[left];
left++;
}
}
return res > n ? 0 : res;
}