LeetCode OJ入门初探-209. Minimum Size Subarray Sum

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.

int minSubArrayLen(int s, int* nums, int numsSize) {
int start=0;
int end = 0;
int sum =0;
int length = end - start +1;
int minlength = numsSize;
sum = nums[0];
if(sum >= s)
return 1;
for(int end= 1;end<numsSize;end++) { sum += nums[end]; if(sum >= s)
{
length = end - start +1;
while(sum >= s)
{
sum -= nums[start];
start++;
length--;
}
length++;
if(length < minlength) minlength = length;
}
}
if(minlength < numsSize)
return minlength;
else
if(start != 0)
return minlength;
else
return 0;
}

 

 

发表评论