Leetcode之Minimum Size Subarray Sum

来源:互联网 发布:php图片$_get 编辑:程序博客网 时间:2024/06/18 05:50

题目描述如下:

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.

求满足和大于等于某个数的最小子数组长度,脑子还是太笨。。

暴力法会TLE,大家都知道。。

于是又上网搜了其他的解法,设置双指针,一前(start)一后(end),end指针往后移动知道sum >=s,然后start指针往后移动,使其在满足sum >= s的条件下不断缩小数组长度;

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            

0 0