描述:
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.
click to show more practice.
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
思路:
1.找到第一符合条件的长度
2.先加上后面的一个元素
3.如果减去前面的一个元素后sum小于target,转到2
3.减去前面的n个元素后符合条件&&减去前面的n+1个元素后不符合条件,获得一个新的长度,跟最小长度相比,小于minLen,更新minLen=newLen
4.若果start<end&&end<nums.length,转至2
代码:
public int minSubArrayLen(int s, int[] nums) { if(nums==null||nums.length==0) return 0; int start=0,end=-1; int sum=0,min=0; int temp=0; while(sum<s&&end<nums.length-1)//找到第一符合条件的长度 sum+=nums[++end]; if(sum<s) return 0; min=end-start+1; while(start<end&&end<nums.length) { if(end+1<nums.length) sum+=nums[++end]; if(sum-nums[start]<s) { if(end==nums.length-1)//已经到达最后 break; else continue;//新加元素后减去开始元素后小于s } while(start<end&&sum-nums[start]>=s)////新加元素后减去开始元素后不小于s sum-=nums[start++]; temp=end-start+1; min=min<temp?min:temp; } return min; }