标签:while next 指针 ret ict one dict 链表 else
哈希表
时间复杂度:O(m+n)
空间复杂度:O(m)或O(n)
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
dict = {}
cur1 = headA
while cur1:
dict[cur1] = 1
cur1 = cur1.next
cur2 = headB
while cur2:
if cur2 in dict:
return cur2
else:
dict[cur2] = 1
cur2 = cur2.next
return None
双指针
时间复杂度:O(m+n)
空间复杂度:O(1)
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
cur1 = headA
cur2 = headB
while cur1!=cur2:
cur1 = cur1.next if cur1 else headB
cur2 = cur2.next if cur2 else headA
return cur1
标签:while next 指针 ret ict one dict 链表 else
原文地址:https://www.cnblogs.com/gugu-da/p/13191679.html