209 .最小サイズ部分配列和

3352 ワード


質問


nの正整数と正の整数sの配列が与えられた場合、その合計の連続したサブアレイの最小長を見つける≥ sが一つでない場合、代わりに0を返します.

例:


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.

解決方法


時間複雑性:O(n)
空間の複雑さ: O ( 1 )
var minSubArrayLen = function(s, nums) {
    let windowSum = 0
    let output = Infinity;
    let windowStart = 0;
    for (let windowEnd = 0; windowEnd < nums.length; windowEnd++) {
      windowSum += nums[windowEnd];
      // shrink the window until the windowSum is smaller than s
      while (windowSum >= s) {
        output = Math.min(output, windowEnd - windowStart + 1);
        // subtract the element at the windowStart index
        windowSum -= nums[windowStart];
        // change windowStart to the next element
        windowStart++; 
      }
    }
    return output == Infinity ? 0 : output;
};