题目描述
Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s. If there isn’t one, return -1 instead.
样例
Given the array [2,3,1,2,4,3] and s = 7, the subarray [4,3] has the minimal length under the problem constraint.
思路
前向双指针。快针定位到大于等于目标值子序列的最后一个元素,慢针再逼近到刚好小于目标值子序列的第一个元素。
代码
class Solution:
"""
@param: nums: an array of integers
@param: s: An integer
@return: an integer representing the minimum size of subarray
"""
def minimumSize(self, nums, s):
# write your code here
if nums is None or s <= 0:
return -1
n = len(nums)
if n == 0: return -1
l = r = t = 0
res = n + 1
while r < n:
while r < n and t < s:
t += nums[r]
r += 1
if t < s: break
while l < r and t >= s:
t -= nums[l]
l += 1
res = min(res, r - l + 1)
if res == n + 1:
return -1
return res
复杂度分析
时间复杂度 O(n) ,空间复杂度 O(1) 。