长度最小的子数组

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35356190/article/details/82951871

给定一个含有 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组如果不存在符合条件的连续子数组,返回 0。

示例: 

输入: s = 7, nums = [2,3,1,2,4,3]
输出: 2
解释: 子数组 [4,3] 是该条件下的长度最小的连续子数组。

进阶:

如果你已经完成了O(n) 时间复杂度的解法, 请尝试 O(n log n) 时间复杂度的解法。

class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        if(s<=0 || nums == null || nums.length<1){
            return 0;
        }
        int sum = 0, count = nums.length+1;
        int i=0, j=0;
        while(nums.length > j || j>i){
            if(sum<s){
                if(j>=nums.length){
                    break;
                }
                sum+=nums[j++];
            }else{
                if(j-i<count){
                    count = j - i;
                }
                sum-=nums[i++];   
            }
        }
        return count == nums.length+1 ? 0 :count;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_35356190/article/details/82951871