Hash table based solution:
Time Complexity = O ( M + N )
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
memo = set()
p1 = headA
p2 = headB
while p1:
memo.add(p1)
p1 = p1.next
while p2:
if p2 in memo:
return p2
p2 = p2.next
return None
No comments:
Post a Comment