【剑指 Offer】剑指 Offer 52. 两个链表的第一个公共节点

本文对比了三种解决链表中两个节点相交问题的方法:经典迭代法、哈希表优化和双指针技巧。哈希法以144ms速度胜出,但内存消耗稍高;双指针实现虽然慢一些,但内存更节省。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目
代码
执行用时: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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值