Leetcode209. 长度最小的子数组

力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

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

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

Leetcode209. 长度最小的子数组_第1张图片

题解:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台 

双指针

代码如下:

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int n = nums.length;
        if(n == 0){
            return 0;
        }
        int left = 0, right = 0;
        int res = Integer.MAX_VALUE;
        int sum = 0;
        while(right < n){
            sum += nums[right];
            while(sum >= target){
                res = Math.min(res, right - left + 1);
                sum -= nums[left];
                left++;
            }
            right++;
        }
        return res == Integer.MAX_VALUE ? 0 : res;
    }
}

 

你可能感兴趣的:(leetcode,双指针)