题目:
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.
代码1:遍历,复杂度O(n^2)
int min(int x,int y)
{
return x<y?x:y;
}
int minSubArrayLen(int s, int* nums, int numsSize)
{
int minlen = 100000;
int count = 0;
int i;
int j;
for(i = 0;i < numsSize;i ++)
{
count+=nums[i];
}
if(count<s)
return 0;
count = 0;
for(i = 0;i<numsSize;i++)
{
count = 0;
for(j = i;j>=0;j--)
{
count += nums[j];
if(s <= count)
{
minlen = min(minlen,i-j+1);
break;
}
}
}
return minlen;
}
C代码2:滑动窗口,复杂度O(n)
int minSubArrayLen(int s, int* nums, int numsSize)
{
int minlen = 100000;
int left = 0;
int right = 0;
int sum = 0;
while (right <= numsSize)
{
if (sum >= s)
sum -= nums[left++];
else
sum += nums[right++];
if (right - left < minlen && sum >= s)
minlen = right - left;
if(right == numsSize && sum < s)
break;
}
return minlen == 100000 ? 0 : minlen;
}
复杂度为O(n*logn)的没想出来,thinking。。。