160. 相交链表 - 力扣(LeetCode)

方法1:暴力法

时间复杂度 :O(m×n)
空间复杂度:O(1)

python 复制代码
# encoding = utf-8
# 开发者:Alen
# 开发时间: 13:10 
# "Stay hungry,stay foolish."

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

# 暴力破解 超出时间限制
class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        # 2026 - 1 - 5 错题集
        currentA = headA
        while currentA: # 遍历到最后currentA为None,while currentA:为False,循环退出
            currentB = headB
            while currentB:
                if currentA == currentB:
                    return currentA
                currentB = currentB.next
            currentA = currentA.next
        return None

方法2:哈希表法

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

python 复制代码
# encoding = utf-8
# 开发者:Alen
# 开发时间: 13:10 
# "Stay hungry,stay foolish."

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

# 哈希表法
class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        # 2026 - 1 - 5 错题集
        seen = set()
        currnt = headA
        while currnt:
            seen.add(currnt)
            currnt = currnt.next

        currnt = headB
        while currnt:
            if currnt in seen:
            # if current in seen_list 这个操作在列表中是线性查找(O(m)),导致整体复杂度为 O(m×n),效率低下。
                return currnt
            currnt = currnt.next
        return None

方法3:双指针法

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

python 复制代码
# encoding = utf-8
# 开发者:Alen
# 开发时间: 13:10 
# "Stay hungry,stay foolish."

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

# 双指针法
class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        # 2026 - 1 - 5 错题集
        p1, p2 = headA, headB
        while p1 != p2:
            if p1:
                p1 = p1.next
            else:
                p1 = headB
            if p2:
                p2 = p2.next
            else:
                p2 = headA

        # 相交点或null(不相交时pA/pB均为null)
        return p1

结果

解题步骤1:www.youtube.com

解题步骤2:www.bilibili.com

相关推荐
始三角龙19 小时前
LeetCode hoot 100 -- 缺失的第一个正整数
算法·leetcode·职场和发展
Sarvartha19 小时前
单链表的顺序建立与结点的删除(期末题复现)
数据结构
gumichef20 小时前
二叉树链式结构的实现
算法·链表·二叉树·队列
战南诚20 小时前
力扣 之 198.打家劫舍
python·算法·leetcode
Dlrb121120 小时前
数据结构-链表
数据结构·链表·逻辑结构·单向链表·物理结构·valgrind工具
小的~~21 小时前
算法题:只出现一次的数字
数据结构·算法
一切皆是因缘际会21 小时前
从概率拟合到内生心智:七层投影架构重构AGI数字生命新范式
大数据·数据结构·人工智能·重构·架构·agi
历程里程碑21 小时前
56 . 高效ET非阻塞IO服务器设计指南
java·运维·服务器·开发语言·数据结构·c++·排序算法
南境十里·墨染春水21 小时前
数据结构 —— 顺序表
数据结构
tongluowan00721 小时前
数据结构 Bitmap(位图)示例 - 用户签到系统
开发语言·数据结构·bitmap·用户签到系统