刷题-Leetcode-209. 长度最小的子数组

209. 长度最小的子数组

题目链接


来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-size-subarray-sum/

题目描述

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

示例:

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


题目分析

暴力法或滑动窗口

此代码使用了滑动窗口

tmp 计算当前连续数组和的最大值

count为当前符合条件的值

res保存最终结果 若res = n +1,认为是没有符合条件的 ,返回0。

class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        //双指针法
        int n = nums.size();
        int i = 0, j = 0;
        int tmp = 0;
        int count = 0;
        int res = n + 1;//如果最后res 仍是n+1  没有符合条件的 返回0
        while(j<n){
            tmp += nums[j];
            j++;
            while(tmp >= target){
                res = min(res, j - i);
                tmp -= nums[i];
                i++;
            }
        }
        return res == n + 1 ? 0 : res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_42771487/article/details/113756825