原题
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.
Follow up:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
解法1
双指针法. 用l, r代表左右两个指针, 使用while循环, 累加total, 当total >= s时, 尽量把l往左移, 找出符合题意的最短的subarray, 跳出内层循环后右指针继续往右走, 直到刷完nums.
Time: O(n)
Space: O(1)
代码
class Solution:
def minSubArrayLen(self, s, nums):
"""
:type s: int
:type nums: List[int]
:rtype: int
"""
if sum(nums) < s: return 0
res = len(nums)+1
l, r, total = 0, 0, 0
while r < len(nums):
total += nums[r]
while total >= s:
# move left to the most-right
res = min(res, r-l+1)
total -= nums[l]
l += 1
r += 1
return res if res != len(nums)+1 else 0
解法2
思路同解法1, 只不过用enumerate()函数简化代码
代码
class Solution:
def minSubArrayLen(self, s, nums):
"""
:type s: int
:type nums: List[int]
:rtype: int
"""
if sum(nums) < s: return 0
res = len(nums)
left, total = 0, 0
for i, n in enumerate(nums):
total += n
while total >= s:
res = min(res, i-left +1)
total -= nums[left]
left += 1
return res