剑指 Offer 52. 两个链表的第一个公共节点
题目描述
https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof
输入两个链表,找出它们的第一个公共节点。
如下面的两个链表:
在节点 c1 开始相交。
示例 1:
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Reference of the node with value = 8
输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
示例 2:
输入:intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
输出:Reference of the node with value = 2
输入解释:相交节点的值为 2 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [0,9,1,2,4],链表 B 为 [3,2,4]。在 A 中,相交节点前有 3 个节点;在 B 中,相交节点前有 1 个节点。
示例 3:
输入:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
输出:null
输入解释:从各自的表头开始算起,链表 A 为 [2,6,4],链表 B 为 [1,5]。由于这两个链表不相交,所以 intersectVal 必须为 0,而 skipA 和 skipB 可以是任意值。
解释:这两个链表不相交,因此返回 null。
注意:
如果两个链表没有交点,返回 null.
在返回结果后,两个链表仍须保持原有的结构。
可假定整个链表结构中没有循环。
程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。
本题与主站 160 题相同:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
解题思路
这个题设定的是一种全新的数据结构,即输入的是一种结尾相同的链表,我们要求的就是两个链表的交点。
方法1:
在这里运用双指针法,设定l1和l2两个指针分别指向两个head,l1遍历完一遍以后连接l2的head,l2遍历完一遍以后连接l1的head,当l1和l2相遇时,位置就是第一个公共节点。
这里需要注意,l1和l2遍历到第一次next为None的时候,要把这个last node记录在数组里。如果l1和l2的last node不一样,说明l1和l2根本没有相交,直接返回None。
方法2:
运用哈希表,遍历第一个链表,把所有节点加入哈希表。
随后遍历第二个链表,如果发现有节点在哈希表中出现过,那么就发现了公共节点
解题代码
方法1:
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
if headA is None or headB is None:
return None
l1, l2 = headA, headB
while l1 != l2:
last_node = []
# 如果l1开始遍历,next走到了None
if l1.next is None:
last_node.append(l1)
if len(last_node) == 2 and last_node[0] != last_node[1]:
return None
l1 = headB
# 如果l1开始遍历,next还没走到None
elif l1.next is not None:
l1 = l1.next
# l2同时来一遍
if l2.next is None:
last_node.append(l2)
if len(last_node) == 2 and last_node[0] != last_node[1]:
return None
l2 = headA
elif l2.next is not None:
l2 = l2.next
# l1和l2最终相遇
return l1
方法1:
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
aSet = set()
node1, node2 = pHead1, pHead2
while node1:
aSet.add(node1)
node1 = node1.next
while node2:
if node2 in aSet:
return node2
node2 = node2.next
执行结果
执行结果:通过
执行用时:504 ms, 在所有 Python3 提交中击败了5.95%的用户
内存消耗:29.5 MB, 在所有 Python3 提交中击败了75.72%的用户
共有 0 条评论