Skip to content

209. 长度最小的子数组 #11

@chasingsnail

Description

@chasingsnail

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

 

示例:

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

进阶:

如果你已经完成了 O(n) 时间复杂度的解法, 请尝试 O(n log n) 时间复杂度的解法。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-size-subarray-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

当窗口内子串和大于等于 s 时,收窄 left,当 count < s 时,记录对比 result 与 right - left

/**
 * @param {number} s
 * @param {number[]} nums
 * @return {number}
 */
var minSubArrayLen = function(s, nums) {
    let result = Infinity
    let count = 0
    let left = 0
    let right = 0
    while (right < nums.length) {
        const curR = nums[right]
        right++
        count += curR
        
        while (count >= s) {
            const curL = nums[left]
            count -= curL
            if (count < s) {
                result = Math.min(right - left, result)
            }
            left++
            
        }
    }
    return result === Infinity ? 0 : result
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions