一天两道力扣(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
        
相关推荐
Navigator_Z13 分钟前
LeetCode //C - 1221. Split a String in Balanced Strings
c语言·算法·leetcode
天疆说23 分钟前
庞特里亚金极小值原理的详细推导
算法
余俊晖36 分钟前
Self-OPD:去掉教师机的流匹配模型 On-Policy 蒸馏
人工智能·算法·机器学习
手写码匠37 分钟前
华为云Flexus+DeepSeek征文|华为云MaaS DeepSeek推理服务 × Flexus云服务器 × Dify一键部署:性能评测实战
人工智能·深度学习·算法·aigc
啥都想学点的研究生1 小时前
一篇文章讲清楚:逻辑回归
算法·机器学习·逻辑回归
货拉拉技术2 小时前
Agent 场景下 Token 成本优化的实战技巧
算法
hahaha60163 小时前
HLS高层次综合设计技巧--循环merge和循环split
人工智能·算法·计算机视觉
JAI科研3 小时前
Deepseek Agent Harness教程(七) | Deepseek Harness不是一个内核加一堆插件
开发语言·人工智能·深度学习·算法·自然语言处理·transformer·vllm
集思广益的灰太狼3 小时前
变频器启动致PLC数据异常?西门子G120配合滤波器EMC抑制方案
人工智能·算法·工控·emc·电磁兼容·变频器·西门子
方方洛3 小时前
vllm教程-03-架构设计
算法·架构