标签:length logs color imu space str instead nim bre
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn‘t one, return 0 instead.
Example:
Input:s = 7, nums = [2,3,1,2,4,3]
Output: 2 Explanation: the subarray[4,3]
has the minimal length under the problem constraint.
1 class Solution { 2 public int minSubArrayLen(int s, int[] nums) { 3 4 int sum = 0; 5 int minLength = nums.length; 6 boolean flag = false; 7 for(int left = 0, right = 0; left < nums.length; ++left) { 8 for(;right < nums.length && sum + nums[right] < s; ++right) { 9 sum += nums[right]; 10 } 11 12 if(right < nums.length && sum + nums[right] >= s) { 13 flag = true; 14 minLength = Math.min(minLength, right - left + 1); 15 } 16 17 sum -= nums[left]; 18 } 19 if(flag) { 20 return minLength; 21 } 22 return 0; 23 } 24 }
Take the right as base,
1 class Solution { 2 public int minSubArrayLen(int s, int[] nums) { 3 int minLength = nums.length; 4 boolean flag = false; 5 int sum = 0; 6 for(int left = 0, right = 0; right < nums.length; ++right) { 7 sum += nums[right]; 8 while(sum >= s) { 9 flag = true; 10 minLength = Math.min(minLength, right - left + 1); 11 sum -= nums[left]; 12 ++left; 13 } 14 } 15 if(!flag) { 16 return 0; 17 } 18 return minLength; 19 } 20 }
Idea 2. Binary search and Cumulative sum for prefix subarray, similar to Subarray Product Less Than K LT713, for each index i, find the smallest right index such that prefix[right] - prefix[i-1] >= s.
1 class Solution { 2 private int findIndex(int[] prefix, int left, int right, int s) { 3 int i = left, j = right; 4 while(i < j) { 5 int mid = i + (j - i)/2; 6 if(prefix[mid] - prefix[left-1] >= s) j = mid; 7 else i = mid + 1; 8 } 9 return i; 10 } 11 12 public int minSubArrayLen(int s, int[] nums) { 13 int[] prefix = new int[nums.length + 1]; 14 for(int i = 1; i < prefix.length; ++i) { 15 prefix[i] = prefix[i-1] + nums[i-1]; 16 } 17 18 boolean flag = false; 19 int minLength = nums.length; 20 for(int i = 1; i < prefix.length; ++i) { 21 int smallestIndex = findIndex(prefix, i, prefix.length, s); 22 if(smallestIndex == prefix.length) { 23 break; 24 } 25 else { 26 flag = true; 27 minLength = Math.min(minLength, smallestIndex - i + 1); 28 } 29 } 30 31 if(!flag) { 32 return 0; 33 } 34 return minLength; 35 } 36 }
Minimum Size Subarray Sum LT209
标签:length logs color imu space str instead nim bre
原文地址:https://www.cnblogs.com/taste-it-own-it-love-it/p/10425219.html