Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.
时间: 2024-03-02 18:54:21 浏览: 69
This problem can be solved using the sliding window technique. We maintain a window of elements whose sum is greater than or equal to the target. We start with two pointers, left and right, both pointing to the first element of the array. We then move the right pointer to the right until the sum of elements in the window is greater than or equal to the target. Once we have found such a window, we update the answer with the length of the current window. We then move the left pointer to the right until the sum of elements in the window is less than the target. We repeat this process until the right pointer reaches the end of the array. We return the answer.
Here is the Python code:
```
def minSubArrayLen(nums, target):
n = len(nums)
left = right = 0
window_sum = 0
ans = float('inf')
while right < n:
window_sum += nums[right]
while window_sum >= target:
ans = min(ans, right - left + 1)
window_sum -= nums[left]
left += 1
right += 1
return ans if ans != float('inf') else 0
```
The time complexity of this algorithm is O(n) and the space complexity is O(1).
阅读全文