笨方法:
class Solution {
public int minSubArrayLen(int s, int[] nums) {
if(nums.length==0)
return 0;
int l=0,r=1,minLength=10000000,currlength;
if(nums[l]>=s||nums[r]>=s) return 1;
if(nums.length==2&&nums[l]+nums[r]<s) return 0;
while(l<=r&&r<nums.length)
{
int sum=0;
for(int i=l;i<=r;i++)
{
sum=sum+nums[i];
}
if(sum>=s)
{
currlength=r-l+1;
l++;
minLength=Math.min(currlength,minLength);
}
else
{
r++;
}
}
return minLength;
}
}
没那么笨:
class Solution {
public int minSubArrayLen(int s, int[] nums) {
if(nums.length==0)
return 0;
int l=0,r=1,minLength=10000000,currlength;
if(nums[l]>=s||nums[r]>=s) return 1;
if(nums.length==2&&nums[l]+nums[r]<s) return 0;
int sum=nums[l]+nums[r];
while(l<=r&&r<nums.length)
{
if(sum<s)
{
if(r==nums.length-1) break;
r++;
sum=sum+nums[r];
}
else
{
sum=sum-nums[l];
currlength=r-l+1;
l++;
minLength=Math.min(currlength,minLength);
}
}
return minLength;
}
}