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.
思路:采用滑动窗口的思想,采用两个指针left和right,right一直向后走,直到数字的和sum大于s,此时right停下来不动,left向后走,不断减小sum的值,直到sum的值小于s(,在left向后走的过程中不断更新minlength的值),此时left不动,right继续向后走,直到sum大于s,然后right停下来,left向后走。。。注意在left向后走的过程中需要不断更新minlength的值。
例如:
0 1 2 3 4 5
数组[ 2 , 3, 1, 2, 4, 3 ] s=7
1)left 和right最开始都为0且sum=0
2)right向后走,直到走到3的位置,有sum=2+3+1+2=8,此时sum大于s,此时right停下来不动,left向前走,先更新minlength的值minlength=right-left=4,sum=sum-nums[0]=6,此时sum小于s,left就不继续往前走了,此时left=1
3)right向后走,此时right=4,sum=sum+nums[4]=10是大于s的,然后right停下来,left继续向前走,sum=sum-nums[1]=7等于s,更新minlength的值,然后sum=sum-nums[2]=6 小于s,left停下来,right继续向后走
4)依此继续下去直到right走到最后,此时minlength的值即为所求。
代码如下:
public class Solution {
public int minSubArrayLen(int s, int[] nums) {
int minlength = Integer.MAX_VALUE;
int left=0;
int right=0;
int length=nums.length;
int sum=0;
while(right<length)
{
while(right<length&& sum<s)
sum=sum+nums[right++];
while(sum>=s&& left<right)
{
minlength=Math.min(minlength,right-left);
sum=sum-nums[left++];
}
}
if(minlength==Integer.MAX_VALUE) return 0;
return minlength;
}
}