Given an array ofnpositive integers and a positive integers, find the minimal length of acontiguoussubarray of which the sum ≥s. If there isn't one, return 0 instead.
For example, given the array[2,3,1,2,4,3]
ands = 7
,
the subarray[4,3]
has the minimal length under the problem constraint.
tag: Two Pointers
class Solution {
public int minSubArrayLen(int s, int[] nums) {
if (nums == null || nums.length == 0) return 0;
int sum = 0, j = 0;
int ans = Integer.MAX_VALUE;
for (int i = 0; i < nums.length; i++){
while (j < nums.length && sum < s){
sum += nums[j++];
}
if (sum >= s){
ans = Math.min(ans, j - i);
}
sum -= nums[i];
}
if (ans < Integer.MAX_VALUE){
return ans;
}
else{
return 0;
}
}
}