一天两道力扣(1)

解法1:

python 复制代码
class Solution(object):
    def getIntersectionNode(self, headA, headB):
        A, B = headA, headB
        while(A != B):
            A = A.next if A else headB
            B = B.next if B else headA 
        return A
        

解析:简单来说就是两个人同时走路,相遇的点就是交叉点,因为相遇了就说明路程一样,两次循环找到交叉点。

解法2:

python 复制代码
class Solution(object):
    def getIntersectionNode(self, headA, headB):
        s = set()
        p, q = headA, headB
        while p:
            s.add(p)
            p = p.next
        while q:
            if q in s:
                return q
            q = q.next
        return None

解析:先将链表A放在哈希表里面,然后遍历B将其逐个与哈希表对比。

解法3:

python 复制代码
class Solution(object):
    def getIntersectionNode(self, headA, headB):
        s1, s2 = [], []
        p, q = headA, headB
        while p:
            s1.append(p)
            p = p.next
        while q:
            s2.append(q)
            q = q.next
        ans = None
        i, j = len(s1) - 1, len(s2) - 1
        while i >= 0 and j >= 0 and s1[i] == s2[j]:
            ans = s1[i]
            i, j = i - 1, j - 1
        return ans
        

解析:用栈先进后出的思想,倒着对比,直到找到不一样的地方。

解法4:

python 复制代码
class Solution(object):
    def getIntersectionNode(self, headA, headB):
        s1, s2 = 0, 0
        p, q = headA, headB
        while p:
            p = p.next
            s1 += 1
        while q:
            q = q.next
            s2 += 1
        p, q = headA, headB
        for i in range(s1 - s2):
            p = p.next
        for i in range(s2 - s1):
            q = q.next
        while p and q and p != q:
            p = p.next
            q = q.next
        return p
        

解析:谁长谁先遍历。先遍历到相同长度,然后直接对比就好了。

python 复制代码
class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        if not root or root == p or root == q: return root
        left = self.lowestCommonAncestor(root.left, p, q)
        right = self.lowestCommonAncestor(root.right, p, q)
        if not left and not right: return
        if not right: return left
        if not left: return right
        return root
        
相关推荐
embrace994 分钟前
【C语言学习】结构体详解
android·c语言·开发语言·数据结构·学习·算法·青少年编程
Ayanami_Reii24 分钟前
基础数学算法-开关问题
数学·算法·高斯消元
稚辉君.MCA_P8_Java34 分钟前
通义 Go 语言实现的插入排序(Insertion Sort)
数据结构·后端·算法·架构·golang
编程小Y1 小时前
配置Associated Domains时,需要注意哪些细节?
职场和发展·蓝桥杯
稚辉君.MCA_P8_Java1 小时前
Gemini永久会员 Go 实现动态规划
数据结构·后端·算法·golang·动态规划
快手技术2 小时前
快手 & 南大发布代码智能“指南针”,重新定义 AI 编程能力评估体系
算法
Murphy_lx2 小时前
C++ std_stringstream
开发语言·c++·算法
CoovallyAIHub2 小时前
超越YOLOv8/v11!自研RKM-YOLO为输电线路巡检精度、速度双提升
深度学习·算法·计算机视觉
哭泣方源炼蛊2 小时前
HAUE 新生周赛(七)题解
数据结构·c++·算法
q***64973 小时前
SpringMVC 请求参数接收
前端·javascript·算法