题目
代码
执行用时:156 ms, 在所有 Python3 提交中击败了26.48% 的用户
内存消耗:29.7 MB, 在所有 Python3 提交中击败了67.33% 的用户
通过测试用例:45 / 45
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
lenA=0
lenB=0
temp_headA=headA
while temp_headA:
lenA+=1
temp_headA=temp_headA.next
temp_headA=headB
while temp_headA:
lenB+=1
temp_headA=temp_headA.next
while lenA>lenB:
lenA-=1
headA=headA.next
while lenA<lenB:
lenB-=1
headB=headB.next
while headB and headA:
if headA==headB:
return headA
headA=headA.next
headB=headB.next
return headB
【方法2】哈希法
执行用时:144 ms, 在所有 Python3 提交中击败了56.29% 的用户
内存消耗:30.1 MB, 在所有 Python3 提交中击败了8.01% 的用户
通过测试用例:45 / 45
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
Node=dict()
while headA:
Node[headA]=1
headA=headA.next
while headB:
if headB in Node:
return headB
headB=headB.next
return None
【方法3:双指针】
执行用时:256 ms, 在所有 Python3 提交中击败了5.11% 的用户
内存消耗:29.7 MB, 在所有 Python3 提交中击败了85.18% 的用户
通过测试用例:45 / 45
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
if not headA or not headB: return None
AA,BB=headA,headB
while AA!=BB:
AA=headB if AA is None else AA.next
BB=headA if BB is None else BB.next
return AA