题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
1. 方法一:哈希集合 判断是否存在公共节点
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # # @param pHead1 ListNode类 # @param pHead2 ListNode类 # @return ListNode类 # class Solution: def FindFirstCommonNode(self , pHead1 , pHead2 ): # write code here if(pHead1==None)|(pHead2==None): return None node1,node2 = pHead1,pHead2 set_A = set() while node1: set_A.add(node1) node1=node1.next while node2: if node2 in set_A: return node2 node2 = node2.next return None
- 记住哈希集合的使用方法:set_A = set()
- 哈希集合判是否存在方法: if node2 in set_A
- Python里面是 if-else-elif 不是 else if
- 这样的空间复杂度比较高,但是相较于数组存储的话,查找效率很高
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # # @param pHead1 ListNode类 # @param pHead2 ListNode类 # @return ListNode类 # class Solution: def FindFirstCommonNode(self , pHead1 , pHead2 ): # write code here if(pHead1==None)|(pHead2==None): return None p1,p2= pHead1,pHead2 while p1!=p2: if p1: p1=p1.next else: p1 = pHead2 if p2: p2 = p2.next else: p2 = pHead1 if p1: return p1 else: return None
双指针算法,一图以言之,两个指针都走了 a+b+c = c + b + a 的路程