问题描述
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之间的数字的和。起始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.
网友评论