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 16:54:21 浏览: 68
js代码-给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。 你可以按任意顺序返回答案。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/two-sum 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
5星 · 资源好评率100%
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).
阅读全文