[LeetCode] 209. Minimum Size Subarray Sum
Given an array of positive integers nums
and a positive integer target
, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr]
of which the sum is greater than or equal to target
. If there is no such subarray, return 0
instead.
Example 1:
Input: target = 7, nums = [2,3,1,2,4,3] Output: 2 Explanation: The subarray [4,3] has the minimal length under the problem constraint.
Example 2:
Input: target = 4, nums = [1,4,4] Output: 1
Example 3:
Input: target = 11, nums = [1,1,1,1,1,1,1,1] Output: 0
Constraints:
1 <= target <= 109
1 <= nums.length <= 105
1 <= nums[i] <= 105
Follow up: If you have figured out the O(n)
solution, try coding another solution of which the time complexity is O(n log(n))
.
长度最小的子数组。
给定一个含有 n 个正整数的数组和一个正整数 target 。
找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/minimum-size-subarray-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题意是给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组,并返回其长度。如果不存在符合条件的连续子数组,返回 0。
还是sliding window的思路做。给两个指针left和right,也用一个变量sum记录遍历到的数字们的加和。遍历的时候一开始也是只移动右指针,当sum >= S的时候,开始试图移动左指针。所谓的最短的子数组也就是左右指针的距离最短,所以每次当sum >= S的时候,需要记录right - left的值。注意有可能最后是找不到一个子数组满足其sum >= S的,如果是这种情况,需要输出0。
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public int minSubArrayLen(int target, int[] nums) { 3 int res = Integer.MAX_VALUE; 4 int start = 0; 5 int end = 0; 6 int sum = 0; 7 while (end < nums.length) { 8 sum += nums[end]; 9 end++; 10 while (sum >= target) { 11 res = Math.min(res, end - start); 12 sum -= nums[start]; 13 start++; 14 } 15 } 16 return res == Integer.MAX_VALUE ? 0 : res; 17 } 18 }
JavaScript实现
1 /** 2 * @param {number} target 3 * @param {number[]} nums 4 * @return {number} 5 */ 6 var minSubArrayLen = function (target, nums) { 7 let left = 0; 8 let right = 0; 9 let sum = 0; 10 let res = Number.MAX_SAFE_INTEGER; 11 while (right < nums.length) { 12 sum += nums[right]; 13 right++; 14 while (sum >= target) { 15 res = Math.min(res, right - left); 16 sum -= nums[left]; 17 left++; 18 } 19 } 20 return res === Number.MAX_SAFE_INTEGER ? 0 : res; 21 };