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 [4,3]
has the minimal length under the problem constraint.
Solution 1 -- Two Pointers
Following the thought of slide window, we apply two 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 right index before getting nums[right], and sum value is nums[0] at beginning.
Time complexity O(n).
1 public class Solution { 2 public int minSubArrayLen(int s, int[] nums) { 3 if (nums == null || nums.length == 0) 4 return 0; 5 int length = 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 return 1; 10 } else { 11 right++; 12 if (right < length) 13 sum += nums[right]; 14 else 15 break; 16 } 17 } else { 18 if (sum < s) { 19 right++; 20 if (right < length) 21 sum += nums[right]; 22 else 23 break; 24 } else { 25 result = Math.min(result, right - left + 1); 26 sum -= nums[left]; 27 left++; 28 } 29 } 30 } 31 if (left == 0 && sum < s) 32 result = 0; 33 return result; 34 } 35 }
时间: 2024-12-28 09:07:20