leetcode 209. 长度最小的子数组

一、题目

给定一个含有 n 个正整数的数组和一个正整数 target 。

找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。

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

二、解法

显然用滑动窗口。

func minSubArrayLen(target int, nums []int) int {
    i:=0
    len:=len(nums)
    sum:=0
    ans:=len+1
    for j:=0;j<len;j++{
        sum+=nums[j]
        for sum>=target{
            curLen:=j-i+1
            if curLen<ans{
                ans=curLen
            }
            sum-=nums[i]
            i++
        }
    }
    if ans==len+1{
        return 0
    }else{
        return ans
    }
}

java:
滑动窗口的经典例题。i,j之间构成滑动窗口,关键在于,每次都是j迭代,然后向前移动i。

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int len=nums.length;
        int i=0,j=0,sum=0;
        int ans=Integer.MAX_VALUE;
        while(j<len){
            sum+=nums[j];
            while(sum>=target){
                ans=Math.min(ans,j-i+1);
                sum-=nums[i];
                i++;
            }
            j++;
        }
        return ans==Integer.MAX_VALUE?0:ans;
    }
}
posted @ 2022-01-06 09:34  livingsu  阅读(38)  评论(0)    收藏  举报