ZhangZhihui's Blog  

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 <= 109
  • 1 <= nums.length <= 105
  • 1 <= 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:

  1. Use two pointers (left and right) to form a sliding window.
  2. Expand the window by moving right and adding nums[right] to total.
  3. Shrink the window from the left (left += 1) once total >= target to find the smallest subarray.
  4. Update min_length whenever a valid subarray is found.
  5. Return the smallest length found or 0 if no valid subarray exists.

Time Complexity:

  • O(n): Each element is processed at most twice (once added and once removed).

 

 

posted on 2025-03-15 01:29  ZhangZhihuiAAA  阅读(20)  评论(0)    收藏  举报