Given an array of positive integers nums and a positive integer target, return the minimal length of a whose 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 <= 1091 <= nums.length <= 1051 <= nums[i] <= 104
ChatGPT's Solution:
class Solution(object): def minSubArrayLen(self, target, nums): """ :type target: int :type nums: List[int] :rtype: int """ left = 0 total = 0 min_length = float('inf') for right in range(len(nums)): total += nums[right] while total >= target: min_length = min(min_length, right - left + 1) total -= nums[left] left += 1 # Shrink the window from the left return min_length if min_length != float('inf') else 0
Explanation:
- Use two pointers (
leftandright) to form a sliding window. - Expand the window by moving
rightand addingnums[right]tototal. - Shrink the window from the left (
left += 1) oncetotal >= targetto find the smallest subarray. - Update
min_lengthwhenever a valid subarray is found. - Return the smallest length found or
0if no valid subarray exists.
Time Complexity:
- O(n): Each element is processed at most twice (once added and once removed).


浙公网安备 33010602011771号