Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

数组5(力扣209): 新增 单个for循环,索引表示起始位置 代码 #2588

Open
hd2yao opened this issue Jun 19, 2024 · 0 comments

Comments

@hd2yao
Copy link

hd2yao commented Jun 19, 2024

只用一个for循环,循环的索引,也可以表示 滑动窗口的起始位置,以下是 go 代码:

func minSubArrayLen(target int, nums []int) int {
    // left 为起始位置
    right, length := 0, 0
    sum := nums[0]
    // 起始位置通过 for 循环来移动
    for left, num := range nums {
        for sum < target {
            right++
            if right < len(nums) {
                sum += nums[right]
            } else {
                goto out
            }
        }
        curLen := right - left + 1
        if length == 0 || (length != 0 && curLen < length) {
            length = curLen
        }
        sum -= num
    }
out:
    return length
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant