코딩 공부/Leetcode

[Python] 160. Intersection of Two Linked Lists

일하는 공학도 2025. 2. 9. 16:08
728x90

난이도 : easy

 

두 개의 linked list가 연결되어있으면, 연결된 위치를 return하는 문제.

 

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
        nodes = set()

        current = headA
        while current:
            nodes.add(current)
            current = current.next

        current = headB
        while current:
            if current in nodes:
                return current
            current = current.next
        
        return None
  1. nodes라는 set를 만들고, headA의 리스트를 nodes에 저장
  2. headB의 리스트를 읽어와서, 만약 nodes에 node가 있으면 그 위치를 return

Runtime : 94ms (12.97%)

Memory : 28.27MB (18.36%)

728x90