問題描述
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 0 instead.
For example, given the array [2,3,1,2,4,3] and s = 7,
the subarray [4,3] has the minimal length under the problem constraint.
問題分析
思路是滑動解決。
設置left荠锭、right兩個指針,total記錄下標在left到right之間的數(shù)字的和。起始left、right均置為0耗溜,向后移動right,直至total大于等于s;向后移動left翁垂,直至total<s,此時right-left+1為subarray的長度硝桩。交替移動right和left沿猜,直到right到達末尾。
AC代碼
class Solution(object):
def minSubArrayLen(self, s, nums):
"""
:type s: int
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if n == 0:
return 0
left = right = total = 0
opt = n+1
while right < n:
while right < n and total < s:
total += nums[right]
right += 1
if total < s:
break
while left < right and total >= s:
total -= nums[left]
left += 1
if right - left + 1 < opt:
opt = right - left + 1
return opt if opt <= n else 0
Runtime: 52 ms, which beats 68.97% of Python submissions.