Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.
Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.
Input: target = 4, nums = [1,4,4]
Output: 1
Input: target = 11, nums = [1,1,1,1,1,1,1,1]
Output: 0
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)).
๋ฐฐ์ด์ ํน์ ๊ตฌ๊ฐ์ ์ ์งํ๋ฉด์ ๊ทธ ๊ตฌ๊ฐ์ ํ์ฅํ๊ฑฐ๋ ์ถ์ํ๋ ๋ฐฉ๋ฒ. ์ด ๋ฌธ์ ์์๋ ์๋์ฐ์ ํฉ์ด target ์ด์์ด ๋ ๋๊น์ง ์ค๋ฅธ์ชฝ ๋์ ํ์ฅํ๊ณ , ๊ทธ ์ดํ์ ์ผ์ชฝ ๋์ ์ค์ฌ๊ฐ๋ฉด์ ์ต์ ๊ธธ์ด๋ฅผ ์ฐพ๋๋ค.
๋ณ์ ์ด๊ธฐํ:
left: ์๋์ฐ์ ์ผ์ชฝ ๋์ ๊ฐ๋ฆฌํค๋ ํฌ์ธํฐ.
sum: ํ์ฌ ์๋์ฐ ๋ด์ ์์๋ค์ ํฉ.
min_length: ์กฐ๊ฑด์ ๋ง์กฑํ๋ ๋ถ๋ถ ๋ฐฐ์ด์ ์ต์ ๊ธธ์ด๋ฅผ ์ ์ฅํ๋ ๋ณ์. ์ฒ์์๋ ๋ถ๊ฐ๋ฅํ ๊ฐ์ธ float('inf')๋ก ์ด๊ธฐํ.
์ค๋ฅธ์ชฝ ๋ ํ์ฅ:
๋ฐฐ์ด nums๋ฅผ ์ํํ๋ฉด์ ๊ฐ ์์๋ฅผ sum์ ๋ํ๋ค.
sum์ด target ์ด์์ด ๋๋ฉด ์๋์ฐ์ ์ผ์ชฝ ๋์ ์ค์ฌ๊ฐ๋ฉด์ min_length๋ฅผ ์
๋ฐ์ดํธ.
์ผ์ชฝ ๋ ์ถ์:
sum์ด target ์ด์์ธ ๋์, ์ผ์ชฝ ๋(left)์ ์ค๋ฅธ์ชฝ์ผ๋ก ์ด๋์ํค๋ฉด์ sum์์ nums[left]๋ฅผ ๋นผ๊ณ , ์๋์ฐ์ ๊ธธ์ด๋ฅผ ์ค์ธ๋ค.
๊ทธ ๊ณผ์ ์์ min_length๋ฅผ ์
๋ฐ์ดํธ.
๊ฒฐ๊ณผ ๋ฐํ:
๋ง์ฝ min_length๊ฐ ๊ฐฑ์ ๋์ง ์์๋ค๋ฉด(์ฌ์ ํ float('inf')๋ผ๋ฉด) ์กฐ๊ฑด์ ๋ง์กฑํ๋ ๋ถ๋ถ ๋ฐฐ์ด์ด ์๋ค๋ ์๋ฏธ์ด๋ฏ๋ก 0์ ๋ฐํ.
๊ทธ๋ ์ง ์์ผ๋ฉด min_length๋ฅผ ๋ฐํ.
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
left = 0
sum = 0
min_length = float('inf')
for right in range(len(nums)):
sum += nums[right]
while sum >= target:
min_length = min(min_length, right - left + 1)
sum -= nums[left]
left += 1
return 0 if min_length == float('inf') else min_length
