[LeetCode] 15.Array and String -Minimum Size Subarray Sum satisfy the conditions and the most kid string

Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.

Example: 

Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.
Follow up:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n). 
 
Learning computer network time, get to the idea of ​​a sliding-window, looking for such a continuous string of title has a good reference value. First term accumulation from the left most array (beginning), and greater than or equal to know input cumulative value, and then begins to decrease from the left (considering the disordered array), the input value is smaller than the slide to the right. Like a long time to think. . .
class Solution {
 public :
 int minSubArrayLen ( int S, Vector < int > & the nums) 
{ 
    // thought sliding window 
    int size = nums.size (); // Get array length 
    int Result = INT_MAX; // define the return result 
    int = sUM 0 ; // calculate the sum for comparison 
    int the begin = 0 ; // sliding window starts 
    for ( int I = 0 ; I <size; I ++ ) 
    { 
        sUM + = the nums [I]; // start array to the right cumulative
        the while (the Sum> = S) { // rightward sliding requirements are met, changing the value of the window start begin 
            Result = min (Result, I - + begin . 1 ); 
            the Sum - = the nums [begin]; 
            begin ++ ; 
        } 
    } 
    return the Result == INT_MAX? 0 : the Result; 
} 
};

 

Guess you like

Origin www.cnblogs.com/hu-19941213/p/11004040.html