[ํŒŒ์ด์ฌ] LeetCode 209. Minimum Size Subarray Sum ๐Ÿ‘‰๐Ÿป Sliding Window / Two Pointers

Youngeui Hongยท2023๋…„ 10์›” 28์ผ
0

์•Œ๊ณ ๋ฆฌ์ฆ˜

๋ชฉ๋ก ๋ณด๊ธฐ
7/12
post-custom-banner

๐Ÿ”— ๋ฌธ์ œ

209. Minimum Size Subarray Sum

๐Ÿ“ ๋‹ต์•ˆ

์•„๋ž˜ ์ฝ”๋“œ๋Š” Sliding Window์˜ ์‚ฌ์ด์ฆˆ๋ฅผ ๋Š˜๋ ธ๋‹ค๊ฐ€ ์ค„์˜€๋‹ค๊ฐ€๋ฅผ ๋ฐ˜๋ณตํ•˜๋ฉด์„œ ์ตœ์†Œ๊ฐ’์„ ์ฐพ๋Š” ์ฝ”๋“œ์ด๋‹ค.

class Solution(object):
    def minSubArrayLen(self, target, nums):
        # ์ดˆ๊ธฐํ™”
        left, right, current_sum, min_len = 0, 0, 0, float('inf')

        while right < len(nums):
            # ํ˜„์žฌ ๋ถ€๋ถ„ ๋ฐฐ์—ด์˜ ํ•ฉ์„ ์—…๋ฐ์ดํŠธ
            current_sum += nums[right]
            right += 1

            # ํ•ฉ์ด ๋ชฉํ‘œ ๊ฐ’๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™์•„์งˆ ๋•Œ๊นŒ์ง€ ์™ผ์ชฝ ํฌ์ธํ„ฐ๋ฅผ ์ด๋™
            while current_sum >= target:
                # ์ตœ์†Œ ๊ธธ์ด ์—…๋ฐ์ดํŠธ
                min_len = min(min_len, right - left)
                # ํ˜„์žฌ ๋ถ€๋ถ„ ๋ฐฐ์—ด์—์„œ ์™ผ์ชฝ ์š”์†Œ๋ฅผ ๋นผ๊ณ  ์™ผ์ชฝ ํฌ์ธํ„ฐ ์ด๋™
                current_sum -= nums[left]
                left += 1

        # ์ตœ์†Œ ๊ธธ์ด๊ฐ€ ์ดˆ๊ธฐ๊ฐ’์ธ ๋ฌดํ•œ๋Œ€๋ฉด 0์„ ๋ฐ˜ํ™˜, ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด ์ตœ์†Œ ๊ธธ์ด ๋ฐ˜ํ™˜
        return 0 if min_len == float('inf') else min_len
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€