LeetCode-209. 长度最小的子数组

LeetCode-209. 长度最小的子数组

难度:中等
给定一个含有 n 个正整数的数组和一个正整数 target 。

找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, …, numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。

class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        int begin=0;    //滑动窗口起始位置
        int end;        //滑动窗口终止位置
        int sum = 0;    //滑动窗口数值之和
        int res = INT_MAX; //滑动窗口最小长度
        for(int i=0;i<nums.size();i++){
            sum += nums[i];
            end = i;
            while(sum >= target){
                res = res < end-begin+1? res : end-begin+1 ;
                if(sum - nums[begin] >= target){
                    sum = sum - nums[begin];
                    begin++;
                    res = res < end-begin+1? res : end-begin+1 ;
                }
                else{
                    break;
                }
            }
        }
        return res < INT_MAX ? res : 0;
    }
};

执行结果:
通过
执行用时:
8 ms, 在所有 C++ 提交中击败了71.22%的用户
内存消耗:
10.3 MB, 在所有 C++ 提交中击败了33.92%的用户
通过测试用例:
19 / 19

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

长不大的程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值