209. 최소 크기 하위 배열 합계

3403 단어


의문:



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;
};

좋은 웹페이지 즐겨찾기