LeetCode---209. Minimum Size Subarray Sum

题目

给出一个数组和目标值s,找出一个连续子序列,使得和不小于目标值。找出长度最小的连续子序列。如:

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.

Python题解

class Solution:
    def minSubArrayLen(self, s, nums):
        """
        :type s: int
        :type nums: List[int]
        :rtype: int
        """
        if sum(nums) < s:
            return 0
        left = cur_sum = 0
        res = len(nums)
        for i, n in enumerate(nums):
            cur_sum += n
            while cur_sum >= s:
                res = min(res, i - left + 1)
                cur_sum -= nums[left]
                left += 1
        return res

猜你喜欢

转载自blog.csdn.net/leel0330/article/details/80520378
今日推荐