当前位置:网站首页>209. Minimum length subarray - sliding window

209. Minimum length subarray - sliding window

2022-04-23 17:32:00 hequnwang10

One 、 Title Description

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 [numsl, numsl+1, …, numsr-1, 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

Two 、 Problem solving

The sliding window

This problem uses a sliding window , First use the right border to move right , When finding a match and greater than target When subscript value of , Then move the left boundary . Indent left boundary , Find the shortest interval

class Solution {
    
    public int minSubArrayLen(int target, int[] nums) {
    
        // The idea of sliding windows 
        int left = 0,right = 0,length = nums.length;
        int sum = 0;
        int minLen = Integer.MAX_VALUE;
        if(length == 0){
    
            return 0;
        }
        while(right<length){
    
            sum += nums[right];
            while(sum >= target){
    
                // Move left border 
                minLen = Math.min(minLen,right-left+1);
                sum -= nums[left];
                left++;
            }
            right++;
        }
        return minLen == Integer.MAX_VALUE?0:minLen;
    }
}

Time complexity :O(n), among n Is the length of the array . The pointer start and end Up to each movement n Time .

Spatial complexity :O(1).

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