209. Minimum Size Subarray Sum
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.
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).
難度:medium
題目:
給定一個包含正整數的陣列和一個正整數s,找出最小長度且元素相連的子陣列使得其和大於s. 如果不存在這樣的子陣列,則返回0.
思路:
滑動伸縮視窗。滑動視窗左邊界為start index, 右邊界為i, 視窗為[start index, i].
Runtime: 2 ms, faster than 99.88% of Java online submissions for Minimum Size Subarray Sum.
class Solution { // O(2n) public int minSubArrayLen(int s, int[] nums) { int sum = 0, startIdx = 0; int minLen = nums.length + 1; for (int i = 0; i < nums.length; i++) { sum += nums[i]; if (sum >= s) { // shrink window while (startIdx <= i && sum >= s) { minLen = Math.min(minLen, i - startIdx + 1); sum -= nums[startIdx++]; } } } return minLen > nums.length ? 0 : minLen; } }