Description: 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.
Link: 209. Minimum Size Subarray Sum
Examples:
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
思路: O(n)复杂度,只遍历一遍,不会啊,没思路。这个视频讲解的很好。首先left=0,然后right指针从0向后移,直到sum(nums[l:r+1]) >= target,然后让left从0向右移,缩小这个sum>=target的区间,更新最小区间的值,直到缩小到其和小于target, 然后right指针再开始右移,循环此过程,直到right指针到nums的尾。
class Solution(object): def minSubArrayLen(self, target, nums): """ :type target: int :type nums: List[int] :rtype: int """ l, s = 0, 0 res = float("inf") for i in range(len(nums)): s += nums[i] while l <= i and s >= target: res = min(res, i-l+1) s -= nums[l] l += 1 if res == float("inf"): return 0 return res
日期: 2021-04-13
Leetcode** 209. Minimum Size Subarray Sum
原文:https://www.cnblogs.com/wangyuxia/p/14655390.html