当前位置:网站首页>leetcode209. Minimum length subarray

leetcode209. Minimum length subarray

2022-07-19 04:26:00 pearz

Address https://leetcode.cn/problems/minimum-size-subarray-sum/
describe : Given a containing n An array of positive integers and a positive integer target .

Find the sum of the array ≥ target The smallest length of Continuous subarray [ n u m s l nums_l numsl, n u m s l + 1 nums_{l+1} numsl+1, …, n u m s r − 1 nums_{r-1} numsr1, n u m s r nums_r numsr] , And return its length . If there is no sub array that meets the conditions , return 0 .

example 1

Input :target = 7, nums = [2,3,1,2,4,3]
Output :2
explain : Subarray [4,3] Is the smallest subarray in this condition .

example 2

Input :target = 4, nums = [1,4,4]
Output :1

example 3

Input :target = 11, nums = [1,1,1,1,1,1,1,1]
Output :0

Ideas : The sliding window
answer

class Solution {
    
    public int minSubArrayLen(int target, int[] nums) {
    
        int len = nums.length;
        int left = 0;
        int sum = 0;
        int res = Integer.MAX_VALUE;

        for (int right = 0; right < len; right++) {
    
            sum += nums[right];
            while (sum >= target) {
    
                res = Math.min(res, right - left + 1);
                sum -= nums[left++];
            }
        }

        return res == Integer.MAX_VALUE ? 0 : res;
    }
}
原网站

版权声明
本文为[pearz]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/200/202207170341126664.html