Question
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 has the [4,3] minimal length under the problem constraint.
Solution 1--pointers
Following the thought of Slide window, we apply the pointers here to solve the problem, one for left and one for right.
If current sum >= target, left++;
If current sum < target, right--;
Remember to check the right index before getting nums[right], and sum value are nums[0] at beginning.
Time complexity O (n).
1 Public classSolution {2 Public intMinsubarraylen (intSint[] nums) {3 if(Nums = =NULL|| Nums.length = = 0)4 return0;5 intLength = nums.length, left = 0, right = 0, result = length, sum = nums[0];6 while(Right <length) {7 if(left = =Right ) {8 if(Nums[left] >=s) {9 return1;Ten}Else { Oneright++; A if(Right <length) -Sum + =Nums[right]; - Else the Break; - } -}Else { - if(Sum <s) { +right++; - if(Right <length) +Sum + =Nums[right]; A Else at Break; -}Else { -result = Math.min (result, Right-left + 1); -Sum-=Nums[left]; -left++; - } in } - } to if(left = = 0 && sum <s) +result = 0; - returnresult; the } *}
Minimum Size Subarray Sum Solution