您的位置:首页 > 其它

LeetCode 209. Minimum Size Subarray Sum

2016-11-03 19:46 405 查看

Problem Statement

(Source) 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.

Solution

Tags:
Two Pointers
.

class Solution(object):
def minSubArrayLen(self, s, nums):
"""
:type s: int
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0

res = float('inf')
start, end, n = 0, 0, len(nums)
window_sum = nums[0]
while end + 1 < n and window_sum < s:
end += 1
window_sum += nums[end]
if window_sum < s:
return 0
while end < n:
while window_sum < s:
if end + 1 < n:
end += 1
window_sum += nums[end]
else:
return res
res = min(res, end - start + 1)
window_sum -= nums[start]
start += 1

return 0 if res == float('inf') else res
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: