Total Accepted: 33397 Total Submissions: 126933 Difficulty: Medium
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).
【抛砖】
时间复杂度O(n)——定义2指针start和end指针,并更新minLen:
1.end先右移,直到第一次满足sum≥s
2.start开始右移,直到第一次满足sum < s:
public int minSubArrayLen(int s, int[] nums) { int start = 0, sum = 0, minLen = Integer.MAX_VALUE; for (int end = 0; end < nums.length; end++) { sum += nums[end]; while (sum >= s) { minLen = Math.min(minLen, end - start + 1); sum -= nums[start++]; } } return minLen; }14 / 14 test cases passed. Runtime: 1 ms Your runtime beats 18.63% of javasubmissions.
时间复杂度O(nlogn)——先求出nums的和函数sum,当sum[i] >= s时,用二分法找到在sum的[0,i]区间中找最右边的小于sum[i] - target的数sum[index]的index,然后求出minLen = i - index,如此不断更新。注意index最小可到-1:
public int minSubArrayLen(int s, int[] nums) { int[] sum = new int[nums.length]; int minLen = Integer.MAX_VALUE; if (nums.length != 0) sum[0] = nums[0]; for (int i = 1; i < nums.length; i++) sum[i] = sum[i - 1] + nums[i]; for (int i = 0; i < nums.length; i++) if (sum[i] >= s) minLen = Math.min(minLen, i - binarySearchLastIndexNotBiggerThanTarget(0, i, sum[i] - s, sum)); return minLen == Integer.MAX_VALUE ? 0 : minLen; } int binarySearchLastIndexNotBiggerThanTarget(int left, int right, int target, int[] sum) { while (left <= right) { int mid = (left + right) >> 1; if (sum[mid] > target) right = mid - 1; else left = mid + 1; } return right; }
14 / 14 test cases passed. Runtime: 3 ms Your runtime beats 6.83% of javasubmissions.