和大于等于 target 的最短子数组

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/2VG8Kg
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

方法一

class Solution {
    public static int minSubArrayLen(int target, int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int n = nums.length;
        int ret = Integer.MAX_VALUE;
        int l = 0, r = 0, sum = nums[0];
        while (r < n) {
            if (sum >= target) {
                ret = Math.min(ret, r - l + 1);
                sum -= nums[l++];
            } else {
                r++;
                sum += r == n ? 0 : nums[r];
            }
        }
        return ret == Integer.MAX_VALUE ? 0 : ret;
    }

    public static void main(String[] args) {
        int[] nums = {2, 3, 1, 2, 4, 3};
        int target = 7;
        System.out.println(minSubArrayLen(target, nums));
    }
}

方法二

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int ans = nums.length + 1;
        int window = 0;
        int left = 0, right = 0;
        while (right < nums.length) {
            window += nums[right++];
            while (window >= target) {
                ans = Math.min(ans, right - left);
                window -= nums[left++];
            }
        }

        return ans > nums.length ? 0 : ans;
    }
}
posted @ 2021-10-20 00:15  Tianyiya  阅读(96)  评论(0)    收藏  举报