当前位置: 首页 > news >正文

一天两道力扣(1)

解法1:

class Solution(object):def getIntersectionNode(self, headA, headB):A, B = headA, headBwhile(A != B):A = A.next if A else headBB = B.next if B else headA return A

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

解法2:

class Solution(object):def getIntersectionNode(self, headA, headB):s = set()p, q = headA, headBwhile p:s.add(p)p = p.nextwhile q:if q in s:return qq = q.nextreturn None

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

解法3:

class Solution(object):def getIntersectionNode(self, headA, headB):s1, s2 = [], []p, q = headA, headBwhile p:s1.append(p)p = p.nextwhile q:s2.append(q)q = q.nextans = Nonei, j = len(s1) - 1, len(s2) - 1while i >= 0 and j >= 0 and s1[i] == s2[j]:ans = s1[i]i, j = i - 1, j - 1return ans

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

 解法4:

class Solution(object):def getIntersectionNode(self, headA, headB):s1, s2 = 0, 0p, q = headA, headBwhile p:p = p.nexts1 += 1while q:q = q.nexts2 += 1p, q = headA, headBfor i in range(s1 - s2):p = p.nextfor i in range(s2 - s1):q = q.nextwhile p and q and p != q:p = p.nextq = q.nextreturn p

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

class Solution(object):def lowestCommonAncestor(self, root, p, q):if not root or root == p or root == q: return rootleft = self.lowestCommonAncestor(root.left, p, q)right = self.lowestCommonAncestor(root.right, p, q)if not left and not right: returnif not right: return leftif not left: return rightreturn root

 

http://www.lryc.cn/news/579680.html

相关文章:

  • 【进阶篇-消息队列】——Kafka如何实现事务的
  • Element 的 Message 多个显示时,只显示一个的封装办法
  • LeetCode 317 最短距离选址问题详解(Swift 实现 + BFS 多源遍历)
  • 从 TCP/IP 协议栈角度深入分析网络文件系统 (NFS)
  • MySQL的窗口函数介绍
  • 基于SpringBoot+Vue的酒类仓储管理系统
  • 【网络协议】WebSocket简介
  • 【tensorflow2.6.0 一系列相关报错记录】
  • 关于微前端框架micro,子应用设置--el-primary-color失效的问题
  • Linux性能分析工具
  • Oracle:报错jdbc:oracle:thin:@IP地址:端口:实例名, errorCode 28001, state 99999
  • Spark 4.0的VariantType 类型以及内部存储
  • 打造一个可维护、可复用的前端权限控制方案(含完整Demo)
  • 2025年4月SCI-吕佩尔狐优化算法Rüppell’s fox optimizer-附Matlab免费代码
  • 苹果手机扫描PDF:整理课堂笔记、保存重要文件
  • Intellij IDEA中Maven的使用
  • H3C-备件流程
  • EXCEL 基础函数
  • 论文阅读笔记——Autoregressive Image Generation without Vector Quantization
  • 构建引擎: 打造小程序编译器
  • 工业路由器赋能智慧电力储能柜实时通讯,构建电力智能化新生态
  • x搜索新增了x-client-transaction-id的验证
  • 网络工具如何帮助消除网络安全风险
  • 通达信 主力资金与成交量分析系统 幅图
  • 机器学习-03(机器学习任务攻略)
  • 边缘计算解决方案:数据中心机房IT设备数据采集与调优
  • STM32-PWM驱动无源蜂鸣器
  • 使用numpy的快速傅里叶变换的一些问题
  • AI+软件测试——03软件的缺陷及管理
  • 一、Docker:一场颠覆应用部署与运维的容器革命