Given an array of n positive integers and a positive integer s, find the minimal
length of a subarray of which the sum ≥ s. If there isn't one, return 0 instead.
For example, given the array [2,3,1,2,4,3] and s = 7,
the subarray [4,3] has the minimal length under the problem constraint.
用一个双层循环就可以得到结果,但明显当数组很大的时候就会超时。
其实想一下,子数组的sum有很大一部分是重复计算,几个元素的和大于等于7,
可以通过减去之前的和的第一个元素,加之后的元素来避免重复计算。
public int minSubArrayLen(int s, int[] nums) {
int result=Integer.MAX_VALUE;
int j=0;
int sum=0;
for(int i=0;i<nums.length;i++){
while(j<nums.length&&sum<s){
sum+=nums[j];
j++;
}
if(sum>=s)
result=Math.min(result, j-i);
sum-=nums[i];
}
return result==Integer.MAX_VALUE?0:result;
}