LeetCode 209.长度最小的子数组

99 阅读1分钟

给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的 连续 子数组,并返回其长度。如果不存在符合条件的子数组,返回 0。

示例:

输入:s = 7, nums = [2,3,1,2,4,3] 输出:2 解释:子数组 [4,3] 是该条件下的长度最小的子数组。

Python

class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        if not nums:
            return 0

        left = right = total = 0
        res = len(nums) + 1

        while right < len(nums):
            total += nums[right]
            
            
            while total >= target:
                res = min(res, right - left + 1)
                total -= nums[left]
                left += 1
            right += 1
        return res if res != len(nums) + 1 else 0

注意:这里是先判断total有没有超过target,如果没有的话再向右移动right指针。

JavaScript

var minSubArrayLen = function(nums, target) {
    let left = right = total = 0
    let res = nums.length + 1
    const n = nums.length

    while (right < n) {
      total += nums[right];
      while (total >= target) {
        res = Math.min(res, right - left + 1);
        total -= nums[left++]
      }
      right++
    }
    return res > nums.length ? 0:res
}