本文共 1219 字,大约阅读时间需要 4 分钟。
题目描述如下:
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.
python代码如下:
class Solution(object): def minSubArrayLen(self, s, nums): """ :type s: int :type nums: List[int] :rtype: int """ if nums == None or len(nums) == 0: return 0 min_length = 0 sum = 0 start = end = 0 while start < len(nums) and end < len(nums): while end < len(nums) and sum < s: sum += nums[end] end += 1 while sum >= s and start <= end: if min_length == 0: min_length = end - start else: min_length = min(min_length, end - start) sum -= nums[start] start += 1 return min_length
转载地址:http://mmbvb.baihongyu.com/