题目描述
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn’t one, return 0 instead.
Example:
Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.
思路分析
这个题不是很难,双指针遍历即可,尾指针顺序扫描数组,同时记录首尾指针之间的数组和,如果满足要求(
≥
s
\geq s
≥s),则进一步判断长度是否比已有的短。扫到一个满足要求的子数组后,我们开始向尾部移动头指针,并做长度更新,直到子数组的和不满足要求。
当尾指针遍历完成后,结束。
Python 代码如下
class Solution:
def minSubArrayLen(self, s: int, nums: List[int]) -> int:
ls = len(nums)
tp1,tp2 =0,0
val, result = 0, ls + 1
while tp2 < ls:
val += nums[tp2]
while val >= s:
result = min(result, tp2-tp1+1)
val -= nums[tp1]
tp1 += 1
tp2 +=1
return result if result <= ls else 0