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

LeetCode-209. 长度最小的子数组,第1张

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

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

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

class Solution {
public:
    int minSubArrayLen(int target, vector& nums) {
        int begin=0;    //滑动窗口起始位置
        int end;        //滑动窗口终止位置
        int sum = 0;    //滑动窗口数值之和
        int res = INT_MAX; //滑动窗口最小长度
        for(int i=0;i= 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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5695412.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存