题目:
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.
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
题意:
给定一个数组和一个目标的和,然后在这个数组中求能达到这个和的最小的子数组的长度。
题解:
一开始LZ理解错了,以为可以将原来的数组重排列的,但是后来经过具体数据的验证,发现不能改变原来的数组,那么就只能老老实实地从头到尾来一步步地加,一步步地逼近结果。考虑两个指针,left和right,分别记录的是子数组的左右的边界;一开始让right右移,直到子数组的和大于或等于给定的值或者是right达到数组末尾,此时我们更新最短距离,同时这个更新我们放在下一个循环中,也就是考虑将left右移一位,然后再在sum中减去原来的值,不停地重复上面的过程,直到right到达末尾为止,且left也到达临界位置。
public class Solution
{
public static int minSubArrayLen(int s,int[] nums)
{
if(nums == null || nums.length == 0)
return 0;
int left = 0,right = 0,sum = 0,length = nums.length,res = length + 1;
while(right < length)
{
while(sum < s && right < length)
{
sum += nums[right++];
}
while(sum >= s)
{
res = Math.min(res, right - left); //这个是用来维护最短距离的
sum -= nums[left++]; //同时这里每次都是减一个数
}
}
return res == length + 1 ? 0 : res; //同时,这里是用来返回具体的距离的
<span style="font-family: Arial, Helvetica, sans-serif;">}</span>
}