一天两道力扣(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
        
相关推荐
203号居民9 分钟前
LeetCode hot 100 —560. 和为 K 的子数组
java·算法·leetcode
文心快码BaiduComate37 分钟前
光本位联合文心快码打造面向光电芯片研发的全栈AI Agent Lightmate
算法
一次旅行1 小时前
ViT/CLIP/LLaVA/GPT-4V/VideoLLM多模态架构全解:原理仿真+工业落地选型+完整推理代码
人工智能·算法·架构
神明不懂浪漫1 小时前
【第五章】队列
开发语言·数据结构·经验分享·笔记·算法
happy_baymax2 小时前
MATLAB MCP Server+ MATLAB Agentic Toolkit+Simulink Agentic Toolkit自动更新批处理文件.ps1
人工智能·算法
神明不懂浪漫2 小时前
【第六章】二叉树
开发语言·数据结构·经验分享·笔记·算法
城管不管2 小时前
第八次面试2026.8.10
面试·职场和发展
橘和柠2 小时前
知识图谱实战(一):数据采集与实体关系抽取(完整代码)
算法
Mem0rin3 小时前
前缀和:中心下标与数组乘积
数据结构·算法