209. Minimum Size Subarray Sum

本文介绍了一个使用滑动窗口技术解决寻找满足特定条件的最小子数组问题的算法。给定一个正整数数组及一个目标和,通过滑动窗口的方法找到连续子数组的最小长度,该子数组的总和大于等于给定的目标值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn’t one, return 0 instead.

For example, given the array [2,3,1,2,4,3] and s = 7,
the subarray [4,3] has the minimal length under the problem constraint.

More practice:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).

class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) {
        int l = 0, r = -1; // nums[l...r]为我们的滑动窗口,初始时窗口不包含任何的元素
        int sum = 0;
        int res = nums.size() + 1; // 连续子数组的最小长度

        // 循环继续的条件:只要左边界小于nums.length,就说明右边界还能取值。也就是说有可能还存在滑动窗口供我们选择
        while (l < nums.size()) {

            // 我们必须保证++r的值依然在数组nums的区间内,也就是r+1<nums.size(),与此同时我们的右边界才能向前拓展一步
            // 否则的话,说明我们的r已经到达数组的最右侧了,它不能够继续向右拓展了,这个时候我们只能让左边界不断的向前了。
            if (r + 1 < nums.size() && sum < s) {
                sum += nums[++r];
            }
            else {
                sum -= nums[l++];
            }

            // sum >= s,说明找到了一个可行的子数组从l到r。
            if (sum >= s) 
                res = min(res, r - l + 1);
        }

        // 说明不存在sum >= s的数组
        if (res == nums.size() + 1) 
            return 0;

        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值