209. 长度最小的子数组

给定一个含有 n 个正整数的数组和一个正整数 target 

找出该数组中满足其总和大于等于 target 的长度最小的 子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,并返回其长度**。**如果不存在符合条件的子数组,返回 0 。

示例 1:

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

示例 2:

**输入:**target = 4, nums = [1,4,4]
**输出:**1

示例 3:

**输入:**target = 11, nums = [1,1,1,1,1,1,1,1]
**输出:**0

提示:


当窗口内和大于target时缩小窗口大小并更新窗口内和,记录窗口大小最小值。直到窗口内和小于target


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {

public:

    int minSubArrayLen(int target, vector<int>& nums) {

        int fast_index=0;

        int slow_index=0;

        int sum=0;

        int length = INT_MAX;

        for(fast_index;fast_index<nums.size();fast_index++)

        {

            sum+=nums[fast_index];

            while(sum>=target)

            {

                length=min(length,fast_index-slow_index+1);

                sum-=nums[slow_index++];

            }

        }

        if(slow_index == 0) return 0;

        return length;

    }

};

上次更新 2025-04-04