Leetcode 160.相交链表

使用python的三种解法

自己解法

拿到题之后,可以想到长链表比短链表要先多走差值步,两者才能同时到达相交点:

  1. 自定义链表长度函数
  2. 求链表长度差值
  3. 让较长的链表先行
  4. 返回交点
class Solution(object):
    def length(self,head):
        cur=head
        l=0
        while cur:
            l+=1
            cur=cur.next
        return l
    
    def getIntersectionNode(self, headA, headB):
        l1=self.length(headA)
        l2=self.length(headB)
        l=headA
        r=headB
        for _ in range(abs(l1-l2)):
            if l1>l2:
                l=l.next
            else:
                r=r.next
        while l:
            if l==r:
                return l
            else:
                l=l.next
                r=r.next
        return None

哈希表方法

  1. 使用哈希表记录一个链表中的结点
  2. 遍历下一个链表的结点
  3. 如果该结点在表中出现过返回结点
  4. 否则,继续迭代
class Solution(object):
    def getIntersectionNode(self, headA, headB):
        hash_set=set()
        cur=headA
        while cur:
            hash_set.add(cur)
            cur=cur.next
        
        curr=headB
        while curr:
            if curr in hash_set:
                return curr
            curr=curr.next
        return None

快慢指针方法

  1. 给不同的链表一个指针
  2. 较短的链表首先到达终点
  3. 将到达终点的指针换到另一个链表的头节点
  4. 最终会在交点相遇

[如图,图片来源于网络,侵删。]

在这里插入图片描述

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        f=headA; s=headB
        while f != s:
            f=f.next if f else headB
            s=s.next if s else headA
        return f
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值