leetcode209-Minimum Size Subarray Sum(最小长度子数组和)

问题描述:

Given an array of n positive integers and a positive integer s, find the minimal length of a 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.

问题求解:

方法一:动态滑窗解决。O(n)时间,O(1)空间。

class Solution {
public://动态滑窗解决。O(n)时间,O(1)空间。
    int minSubArrayLen(int s, vector<int>& nums) {
        int n=nums.size();
        int cur_sum = 0;//当前的和
        int min_size = INT_MAX;//子数组最小长度
        int begin = 0, end = 0;//子数组起始位置
        while(begin < n)
        {   
            if(cur_sum<s && end<n)
            {//(1)如果当前窗口的数相加没有达到s,则将窗口右移
                cur_sum += nums[end++];
            }
            else if(cur_sum >= s)
            {//(2)如果当前窗口的数相加等于或大于s,则收缩窗口
                min_size = min(min_size, end-begin);//实为(end-1)-begin+1,之前end已经多加1。
                cur_sum -= nums[begin++];
            }
            else
            {//(3)cur_sum < s而且end>=n,则退出循环
                break;
            }
        }
        return (min_size==INT_MAX)?0:min_size;
    }
};

方法二:在一的基础上简化下逻辑。其他不变。

class Solution {
public://动态滑窗解决。O(n)时间,O(1)空间。
    int minSubArrayLen(int s, vector<int>& nums) {
        int n=nums.size();
        if(n == 0) return 0;
        int min_size=INT_MAX;
        int cur_sum=0;
        int begin=0;
        for(int end=0;end<n;end++)
        {//依次遍历
            //1.更新当前窗口和
            cur_sum += nums[end];
            while(cur_sum >= s)
            {//2.如果当前和大于或等于s
                //(1)更新最小长度
                min_size = min(min_size, end-begin+1);
                //(2)当前和减去窗口最前的数,并且窗口前指针后移
                cur_sum -= nums[begin++];
            }
        }
        return (min_size==INT_MAX)?0:min_size;
    }
};
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值