ํˆฌ ํฌ์ธํ„ฐ(Two Pointers)

  • ์–ด๋–ค ํŠน์ • ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋Š” ์—ฐ์† ๊ตฌ๊ฐ„์„ ๊ตฌํ•  ๋•Œ O(N)์œผ๋กœ ํ’€ ์ˆ˜ ์žˆ๋‹ค.
  • 2๊ฐœ์˜ ํฌ์ธํ„ฐ๋ฅผ ์กฐ์ž‘ํ•ด๊ฐ€๋ฉฐ ์›ํ•˜๋Š” ๋‹ต์„ ์–ป๋Š”๋‹ค.

image


Python ์ฝ”๋“œ

LeetCode์˜ 3๋ฒˆ ๋ฌธ์ œ๋ฅผ two-pointers๋กœ ํ‘ผ ์ฝ”๋“œ์ด๋‹ค. l, r ๋‘ ๊ฐœ์˜ ํฌ์ธํ„ฐ ๋ชจ๋‘ 0๋ถ€ํ„ฐ ์‹œ์ž‘ํ•œ๋‹ค. ๋”•์…”๋„ˆ๋ฆฌ์— ์ธ๋ฑ์Šค์™€ ๋ฌธ์ž๋ฅผ ๊ฐ™์ด ์ €์žฅํ•œ๋‹ค. ๋งŒ์•ฝ ๋ฌธ์ž๊ฐ€ ๋”•์…”๋„ˆ๋ฆฌ์— ์žˆ๋Š” ๊ฒฝ์šฐ l ํฌ์ธํ„ฐ๋ฅผ ์ค‘๋ณต๋œ ๋ฌธ์ž ๋‹ค์Œ ์ธ๋ฑ์Šค์™€ ํ˜„์žฌ ์œ„์น˜ ์ค‘ ์ธ๋ฑ์Šค๊ฐ€ ํฐ ๊ณณ์œผ๋กœ ์˜ฎ๊ธด๋‹ค. ์ด๋Š” ํ•ญ์ƒ ์˜ค๋ฅธ์ชฝ์œผ๋กœ ๊ฐ€๋Š” ๊ฒƒ์„ ๋ณด์žฅํ•˜๊ธฐ ์œ„ํ•จ์ด๋‹ค. ๋ฌธ์ž๋ฅผ ํ™•์ธ ํ•  ๋•Œ๋งˆ๋‹ค ํ˜„์žฌ ๊ธธ์ด์™€ longest ๊ฐ’์„ ๊ณ„์†ํ•ด์„œ ๋น„๊ตํ•˜๋ฉฐ ์ตœ๋Œ€ ๊ธธ์ด๋ฅผ ์ฐพ๋Š”๋‹ค. r ํฌ์ธํ„ฐ๋Š” ์ผ์ •ํ•˜๊ฒŒ 1์”ฉ ์ฆ๊ฐ€ํ•˜๋ฉฐ, l ํฌ์ธํ„ฐ๋Š” ์ค‘๋ณต๋œ ๊ฐ’์ด ๋ฐœ๊ฒฌ๋  ๋•Œ ์›€์ง์ธ๋‹ค.


def lengthOfLongestSubstring(self, s):
    seen = {}
    l, r = 0, 0
    longest = 1

    while r < len(s):
        if s[r] in seen:
            l = max(l, seen[r] + 1)
        longest = max(longest, r - l + 1)
        seen[s[r]] = r
        r += 1

    return longest


๊ทธ๋ฆฌ๊ณ  LeetCode์˜ 11๋ฒˆ๋ฌธ์ œ๋„ ํˆฌํฌ์ธํ„ฐ ๋ฌธ์ œ๋‹ค. ๊ทธ๋ž˜ํ”„์˜ ๋งจ์™ผ์ชฝ๊ณผ ๋งจ์˜ค๋ฅธ์ชฝ์„ left, right ํฌ์ธํ„ฐ๋กœ ๋‘”๋‹ค. left์™€ right ์ค‘์— ์งง์€ ํฌ์ธํ„ฐ๋ฅผ ํ•œ์นธ์”ฉ ์˜ฎ๊ธฐ๋ฉด์„œ ์ง์‚ฌ๊ฐํ˜• ๋ฉด์ ์˜ ์ตœ๋Œ“๊ฐ’์„ ๊ตฌํ•œ๋‹ค. left, right ํฌ์ธํ„ฐ๊ฐ€ ๋งŒ๋‚ฌ์„ ๋•Œ ์ข…๋ฃŒํ•œ๋‹ค. Brute-force๋ฅผ ์“ฐ๋ฉด ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋œจ๊ธฐ ๋•Œ๋ฌธ์— ํˆฌํฌ์ธํ„ฐ๋ฅผ ์‚ฌ์šฉํ•ด์„œ O(N)์œผ๋กœ ํ•ด๊ฒฐํ•ด์•ผ ํ•œ๋‹ค.


    def maxArea(self, height):
        l, r, maxArea = 0, len(height)-1, 0
        while l < r:
            if height[l] < height[r]:
                maxArea = max(maxArea, height[l]*(r-l))
                l += 1
            else:
                maxArea = max(maxArea, height[r]*(r-l))
                r -= 1
        return maxArea


์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„์šฐ(Sliding Window)

  • ํˆฌ ํฌ์ธํ„ฐ์™€ ๋น„์Šทํ•œ ์œ ํ˜•์ด๋‹ค.
  • ํˆฌ ํฌ์ธํ„ฐ์™€๋Š” ๋‹ฌ๋ฆฌ ํ•ญ์ƒ ๊ตฌ๊ฐ„์˜ ๊ธธ์ด๊ฐ€ ๊ฐ™๋‹ค๋Š” ์ฐจ์ด์ ์ด ์žˆ๋‹ค.
  • ๋”ฐ๋ผ์„œ ํˆฌ ํฌ์ธํ„ฐ๋Š” ๊ตฌ๊ฐ„ ์–‘์ชฝ ๋์ด ๋˜๋Š” ํฌ์ธํ„ฐ๊ฐ€ 2๊ฐœ ํ•„์š”ํ•œ ๋ฐ˜๋ฉด, ์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„์šฐ๋Š” ๊ตฌ๊ฐ„์˜ ๊ธธ์ด๊ฐ€ ๊ณ ์ •๋˜์–ด ์žˆ์œผ๋ฏ€๋กœ ํฌ์ธํ„ฐ๊ฐ€ 2๊ฐœ์ผ ํ•„์š”๋Š” ์—†๋‹ค.


Reference