Leetcode209 title subarray minimum length

topic

Given a positive integer with n a positive integer and an array of s, find the array satisfies its minimum length and a successive sub-arrays of ≥ s. If successive sub-array qualifying does not exist, 0 is returned.

Examples

Input: S =. 7, the nums = [2,3,1,2,4,3 ] 
Output: 2 
Explanation: subarray [ 4,3] is the smallest length of a contiguous subarray under this condition.

 

answer

This problem can be solved using two-hand method, using the double pointer maintains a sliding window, when the sub-array is greater than s in the window and the left pointer is moved forward, when s is smaller than the right pointer is moved forward.

class Solution {
     public  int minSubArrayLen ( int s, int [] the nums) {
         / * 
        this question using a two-hand method to maintain a sliding window, when the sub-array within the window and is larger than s is moved left pointer, when less than s moves the right pointer 
        
        
        * / 
        int len = nums.length;
         int SUM = 0 ;
         int left = 0 ;
         int right = 0 ;
         int Result = nums.length +. 1 ;
         the while (right < len) {
             the while (SUM <S && right <len ) {     // sliding the sliding window sub-arrays and the target value is greater than the right and the right pointer 
                sum + =the nums [right]; 
                right ++ ; 
            } 
            the while (SUM> = S) {     // sliding window sub-array and the target value or less, the left pointer slides to the right, and solving a minimum length 
                result = Math.min (result, right - left); 
                SUM - = the nums [left]; 
                left ++ ; 
            } 
        } 
        return Result == (+ nums.length. 1) 0:? Result;     // special situation is determined, and if s is greater than an entire array directly return 0 
    } 
}

 

Guess you like

Origin www.cnblogs.com/jianglinliu/p/11831333.html