Skip to content

Latest commit

 

History

History
24 lines (24 loc) · 658 Bytes

209长度最小的子数组.md

File metadata and controls

24 lines (24 loc) · 658 Bytes

滑动窗口双指针实现O(n):

func minSubArrayLen(target int, nums []int) int {
    // 滑动窗口
    left, sum := 0, 0
    res := len(nums) + 1 // 用来最后判断是否无符合的子数组
    for right := 0; right < len(nums); right++ {
        sum += nums[right]
        for sum >= target {
            subLength := right - left + 1 // 目前的窗口长度
            if subLength < res {
                res = subLength
            }
            sum -= nums[left] // 去掉最左边的数,准备向右滑动
            left++
        }
    }
    if res == len(nums) + 1 {
        return 0
    } else {
        return res
    }
}