Published:
Updated:

  • Reference
  • ์‹œ๊ฐ„๋ณต์žก๋„: $O(N)$


Solution

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None


class Solution(object):
    # 2๊ฐœ์˜ ๋งํฌ๋“œ๋ฆฌ์ŠคํŠธ ๊ต์ฐจํ•˜๋Š” ๋ถ€๋ถ„ ์ฐพ๊ธฐ
    # ๋งŒ์•ฝ, ๊ต์ฐจํ•˜๋Š” ๋ถ€๋ถ„ ์—†์œผ๋ฉด 0 ๋ฆฌํ„ด
    def getIntersectionNode(self, headA, headB):
        # ๊ต์ฐจ๋˜๋Š” ๋ถ€๋ถ„ ์—†์œผ๋ฏ€๋กœ 0 ๋ฆฌํ„ด
        if headA is None or headB is None:
            return None

        # ํ˜„์žฌ A, B๊ฐ€ ๊ณ„์† ๋ฐ”๋€” ๊ฒƒ์ด๋ฏ€๋กœ ๋ณ€์ˆ˜ ์ง€์ •
        currentA = headA
        currentB = headB

        # ํ˜„์žฌ์˜ A์™€ B๊ฐ€ ๋‹ค๋ฅผ ๋•Œ ๊ณ„์† ๋ฐ˜๋ณต๋ฌธ ๋Œ์•„์ฃผ๊ธฐ
        while currentA != currentB:
            # ํ˜„์žฌ A๊ฐ€ ์žˆ์œผ๋ฉด ๋‹ค์Œ์œผ๋กœ ๊ฐ€๊ณ 
            if currentA:
                currentA = currentA.next
            # A๊ฐ€ ์—†์œผ๋ฉด B๋กœ ๊ฐ
            else:
                currentA = headB

            # B๋„ ์œ„์™€ ๋˜‘๊ฐ™์ด ์ง„ํ–‰
            if currentB:
                currentB = currentB.next
            else:
                currentB = headA

        # ๊ฒฐ๋ก ์€ A์™€ B๊ฐ€ ๊ฐ™์€ ์ง€์ ์—์„œ ๋งŒ๋‚  ๋•Œ ๋ฐ˜๋ณต๋ฌธ์ด ๋น ์ ธ๋‚˜์˜ค๋„๋ก ํ–ˆ๋‹ค.
        # ์ง์ ‘ ์˜ˆ์ œ๋ฅผ ๊ฐ€์ง€๊ณ  ๋…ธ๋“œ์˜ ํ•˜๋‚˜์”ฉ ์ด๋™์‹œ์ผœ๋ณด๋ฉด ์ดํ•ดํ•  ์ˆ˜ ์žˆ๋‹ค.
        # "else"์—์„œ์˜ ๋กœ์ง์ด ํ•ต์‹ฌ ๋กœ์ง -> A๋‚˜ B๊ฐ€ null์ด ๋˜๋ฉด ๊ทธ ์ƒ๋Œ€ node๋กœ ์ด๋™ํ•œ๋‹ค๋Š” ๋œป
        # ์œ„์™€ ๊ฐ™์€ ๋ฐฉ์‹์œผ๋กœ ๊ฒฐ๊ตญ ๋งž๋ฌผ๋ฆฌ๋Š” ์ง€์ ์ด ์ƒ๊ธฐ๊ฒŒ ๋จ
        return currentA

Leave a comment