第八周:[leetcode] 209. Minimum Size Subarray Sum

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.

问题描述:返回长度最短,序列之和大于s的连续序列的长度;
解题思路:维护l、r分别保存序列的起始结束下标,依次扫描所给数组,当sum < s 时,r+=1,当sum > s时,l+=1,直至扫描结束。

    int minSubArrayLen(int s, vector<int>& nums) {
        if(nums.empty()) return 0;
        int sum = 0;
        int ans = INT_MAX, count = 0;
        int l = 0, r = 0;
        while(r < nums.size() || sum >= s ){
            //当序列和小于s时,r++
            if(sum < s){
                sum += nums[r++];
                count++;
            }
            //当序列长度大于当前最短序列的长度或序列和大于s时,l++
            if(sum >= s || count > ans){
                ans = min(ans, count);
                //如果长度为1,则直接返回
                if(ans == 1)return ans;
                sum -= nums[l++];
                count--;
            }
        }
        if(ans == INT_MAX) return 0;
        return ans;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值