209. Minimum Size Subarray Sum

本文介绍了一种算法,用于寻找给定数组中满足特定条件的最短连续子数组。通过移动双指针的方式,实现时间复杂度O(n)和空间复杂度O(1),并附带了详细的C++代码实现。

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,求数组里连续子序列和>=s,并使得这个连续子序列长度最小。

思想:由于是连续的子序列 可以定义2个指针start,end,tempsum为数组[start....end]之和的值,min为所有tempsum>=s的最小值

  移动end或start指针

  若数组[start....end]之和<s 那么指针end++;

  若数组[start....end]之和>s 判断min是否是最小值 然后指针start++; 

  找到tempsum>=s时的最小值min

C++ AC代码:Time O(n) Space O(1)   这次有些判断不到位,导致代码复杂度比较高,还需加强训练!!!

class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) {
        int len = nums.size();
        if(len<=0) return 0;
        int min = len;
        int b = 0;
        int e = 0;
        int tempsum = nums[0];
        while(b<=e&&e<len){
            if(e==b&&nums[e]>=s)
                return 1;
            else if(e==b&&nums[e]<s){
                    e++;
                    tempsum +=nums[e];
            }
            else if(e!=b&&tempsum>=s){
                min = min<(e-b+1)?min:(e-b+1);
		if(e==len-1&&tempsum-nums[b]<s)
			break;
                tempsum-=nums[b];
                b++;
            }else if(e!=b&&tempsum<s){
                e++;
		if(e==len)
			break;
                tempsum +=nums[e];
            }
        }
        min = (tempsum>=s||min!=len)?min:0;
        return min;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值