209. Minimum Size Subarray Sum

来源:互联网 发布:真心话大冒险软件 编辑:程序博客网 时间:2024/06/07 10:02

题意: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.

思路:就用可变滑动窗口的方法,如果窗口中数字和大于s,就把窗口左边界不断向右移即可。

class Solution:    def minSubArrayLen(self, s, nums):        start = 0        sum = 0        min_size = float("inf")        for i in xrange(len(nums)):            sum += nums[i]            while sum >= s:                min_size = min(min_size, i - start + 1)                sum -= nums[start]                start += 1        return min_size if min_size != float("inf") else 0
0 0