首页 > 其他 > 详细

相交链表判断

时间:2020-06-25 14:56:06      阅读:80      评论:0      收藏:0      [点我收藏+]

方法1:

哈希表

时间复杂度:O(m+n)

空间复杂度:O(m)或O(n)

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        dict =  {}
        cur1 = headA
        while cur1:
             dict[cur1] = 1
             cur1 = cur1.next
        cur2 = headB
        while cur2:
            if cur2 in dict:
                return cur2
            else:
                dict[cur2] = 1
            cur2 = cur2.next
        return None

方法2:

双指针

时间复杂度:O(m+n)

空间复杂度:O(1)

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        cur1 = headA
        cur2 = headB
        while cur1!=cur2:
            cur1 = cur1.next if cur1 else headB
            cur2 = cur2.next if cur2 else headA
        return cur1

相交链表判断

原文:https://www.cnblogs.com/gugu-da/p/13191679.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!