一天两道力扣(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
        
相关推荐
帅帅爱数学1 天前
DeepMimic论文详细解析:基于示例引导的深度强化学习实现物理仿真角色技能
算法·强化学习
Dream it possible!1 天前
LeetCode 面试经典 150_哈希表_快乐数(45_202_C++_简单)(哈希表;快慢指针)
leetcode·面试·散列表
IT成长日记1 天前
【LVS入门宝典】LVS调度算法轮询(RR)深度解析:从原理到实战的公平调度之道
算法·lvs·rr·轮询调度算法
NAGNIP1 天前
一文搞懂量化、剪枝和知识蒸馏都是什么?
算法
点云SLAM1 天前
GTSAM 中自定义因子(Custom Factor)的详解和实战示例
算法·机器人·slam·后端优化·gtsam·gtsam自定义因子·因子图
学历真的很重要1 天前
Claude Code 万字斜杠命令指南
后端·语言模型·面试·职场和发展·golang·ai编程
萘柰奈1 天前
LeetCode刷题记录----62.不同路径(Medium)
算法·leetcode·职场和发展
阳光明媚sunny1 天前
爬楼梯算法java实现
算法·动态规划
天才测试猿1 天前
Python常用自动化测试框架—Pytest详解
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
贝塔实验室1 天前
LDPC码的概念
科技·学习·程序人生·算法·学习方法·程序员创富·改行学it