Leetcode Hot100之链表
1.相交链表
- 解题思路
快慢指针:分别求出两个链表的长度n1和n2,在长度较长的那个链表上,快指针先走n2 - n1,慢指针再出发,最后能相遇则链表相交
时间复杂度O(m+n),空间复杂度O(1) - 代码
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = Noneclass Solution:def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:if not headA or not headB:return Nonel_a = 0l_b = 0node = headAwhile node:l_a += 1node = node.nextnode = headBwhile node:l_b += 1node = node.nextnode1 = headA node2 = headBif l_b > l_a:l_a, l_b = l_b, l_anode1, node2, = node2, node1for _ in range(l_a - l_b):node1 = node1.nextwhile node1 and node2:if node1 == node2:return node1node1 = node1.nextnode2 = node2.nextreturn None
2.翻转链表
- 解题思路
最基本的题目,一定要掌握。prev初始化成None,不需要dummy_head
时间复杂度O(N),空间复杂度O(1) - 代码
class Solution:def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:if not head:return head# prev直接初始化成None就好prev = Nonecur = headnex = Nonewhile cur:nex = cur.nextcur.next = prevprev = curcur = nexreturn prev
3.回文链表
- 解题思路
查找中间链表,然后翻转后半段,接着使用双指针比较判断即可
时间复杂度O(N),空间复杂度O(1) - 代码
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution:def isPalindrome(self, head: Optional[ListNode]) -> bool:def reverse(head):if not head:return headprev = Nonecur = headnex = Nonewhile cur:nex = cur.nextcur.next = prevprev = curcur = nexreturn previf not head:return Falseif not head.next:return Trueslow = headfast = head.nextwhile fast and fast.next:slow = slow.nextfast = fast.next.nexthead2 = reverse(slow.next)node_1 = headnode_2 = head2while node_1 and node_2:if node_1.val != node_2.val:return Falsenode_1 = node_1.nextnode_2 = node_2.nextreturn True
4. 环形链表
- 题目描述
判断链表是否有环 - 解题思路
快慢指针,快指针一次走一步,慢指针一次走两步,如果有环的话,他们一定在环中相遇。类比于操场跑圈的套圈,对于slow来说,fast是一个节点一个节点的靠近slow的
时间复杂度:O(N),
空间复杂度:O(1)。 - 代码
class Solution:def hasCycle(self, head: Optional[ListNode]) -> bool:if not head or not head.next:return Falsefast = slow = headwhile fast and fast.next:slow = slow.nextfast = fast.next.nextif slow == fast:return Truereturn False
5. 环形链表2
- 题目描述
如果链表有环需要返回入环的节点,无环返回None - 解题思路
图片来自代码随想录;查找是否有环和上一题目一样,使用快慢指针,如果有环,那么他们一定在环内相遇。如下图所示,慢指针走过的路程是x + y,快指针走过的路程是 x + y + (y + z) * n,又因为快指针走的路程是慢指针的两倍,因此有x + y + (y + z) * n = 2* (x + y), 也就是(y + z) * n = x + y, 也就是(y+z)*(n-1) + z = x,那么如果两个节点分别从头结点和相遇节点出发,一定可以在入口节点处相遇;
时间复杂度:O(N),
空间复杂度:O(1)。 - 代码
class Solution:def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:if not head or not head.next:return Noneslow = fast = headhas_cycle = Falsewhile fast and fast.next:slow = slow.nextfast = fast.next.nextif fast == slow:has_cycle = Truebreakif not has_cycle:return Nonenode1 = headnode2 = slowwhile node1 != node2:node1 = node1.nextnode2 = node2.nextreturn node1
6. 合并两个有序链表
- 解题思路
是链表排序和合并K个有序链表等题目要用的基本模块
时间复杂度O(n+m), 空间复杂度O(n+m) - 代码
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution:def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:if not list1:return list2if not list2:return list1head = ListNode()cur = headnode1 = list1node2 = list2while node1 and node2:if node1.val < node2.val:cur.next = node1node1 = node1.nextelse:cur.next = node2node2 = node2.nextcur = cur.nextif node1:cur.next = node1if node2:cur.next = node2return head.next
7. 两数相加
-
题目描述
-
解题思路
注意考虑进位、两个数字位数不同的情况
时间复杂度:O(max(m,n)),其中 m 和 n 分别为两个链表的长度。我们要遍历两个链表的全部位置,而处理每个位置只需要 O(1) 的时间。
空间复杂度:O(1)。注意返回值不计入空间复杂度。 -
代码
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution:def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:if not l1:return l2if not l2:return l1prev = 0n1 = n2 = 0new_head = ListNode()node1 = l1node2 = l2cur = new_headwhile node1 or node2:n1 = node1.val if node1 else 0n2 = node2.val if node2 else 0s = n1 + n2 + prevnode = ListNode(s % 10)prev = s // 10cur.next = nodecur = cur.nextif node1:node1 = node1.nextif node2:node2 = node2.nextif prev != 0:node = ListNode(prev)cur.next = nodereturn new_head.next
8. 删除链表的倒数第N个节点
- 解题思路
快慢指针,快指针先走N,然后快慢一起走,当快指针走到末尾时,慢指针指向的就是要删除的节点 - 代码
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution:def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:if not head:return Nonenew_head = ListNode(0, head)prev = new_headslow = fast = headfor i in range(n):if not fast:raise ValueError("n must greter than length of list")fast = fast.nextwhile fast:prev = slowslow = slow.nextfast = fast.nextprev.next = slow.nextreturn new_head.next
9. 两两交换链表中的节点
- 题目描述
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。 - 解题思路
模拟两两交换的过程即可 - 代码
class Solution:def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:if not head:return headnew_head = ListNode(next=head)cur = headprev = new_headwhile cur and cur.next:next = cur.nextcur.next = next.nextnext.next = curprev.next = nextprev = curcur = prev.nextreturn new_head.next
10. k个一组翻转链表
-
题目描述
给你链表的头节点 head ,每 k 个节点一组进行翻转,请你返回修改后的链表。k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
-
解题思路
将前k个节点切断成一个链表,进行翻转,并递归对剩下的链表进行‘k个一组翻转链表’操作,再将两个链表连起来,即可 -
代码
class Solution:def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:def reverse(head):if not head:return headprev = Nonecur = headnex = Nonewhile cur:nex = cur.nextcur.next = prevprev = curcur = nexreturn previf not head:return headl = 0node = headwhile node:l += 1node = node.nextif l < k:return headnode = headfor i in range(k - 1):node = node.nextnew_head = node.nextnode.next = Nonereverse_head = reverse(head)head.next = self.reverseKGroup(new_head, k)return reverse_head
11. 随机链表的复制
- 解题思路
第一遍循环,复制每个节点,并把他们通过next连接成一个普通的链表,同时构建哈希表,哈希表的key是旧的节点,value是复制的节点;
第二遍循环,通过哈希表完成random的指定,注意random可能是空的
时间复杂度O(N), 空间复杂度O(N) - 代码
class Solution:def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':if not head:return headdic = {}node = headnew_head = Node(0)prev = new_headwhile node:new_node = Node(x=node.val)prev.next = new_nodedic[node] = new_nodeprev = new_nodenode = node.nextnode = headwhile node:# 一定要注意原始节点的random是不是空的if node.random:dic[node].random = dic[node.random]node = node.nextreturn new_head.next
12. 排序链表
-
题目描述
-
解题思路
解题思路:归并排序的思想,找到中间节点,然后分别对左右两边进行排序,最后合并左右两边的有序链表。
这道题目的关键:1. 找到链表的中间节点:用快慢指针实现,慢指针一次走一步,快指针一次走两步,当快指针走到末尾时,慢指针指向的就是中间节点(不用求出链表长度再计算中间节点的位置);2.将链表从中间节点切断成两个链表;3. 合并两个有序链表。
时间复杂度:O(nlogn),其中 n 是链表的长度。
空间复杂度:O(logn),其中 n 是链表的长度。空间复杂度主要取决于递归调用的栈空间。 -
代码
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution:def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:def merge(l1, l2):if not l1:return l2if not l2:return l1head = ListNode()cur = headnode1 = l1node2 = l2while node1 and node2:if node1.val < node2.val:cur.next = node1node1 = node1.nextelse:cur.next = node2node2 = node2.nextcur = cur.nextif node1:cur.next = node1if node2:cur.next = node2return head.nextif not head or not head.next:return head# 找到中间节点的方法:快慢指针slow = headfast = head.nextwhile fast and fast.next:slow = slow.nextfast = fast.next.nextnode1 = headnode2 = slow.next# 从中间断开链表slow.next = Nonehead1 = self.sortList(node1)head2 = self.sortList(node2)return merge(head1, head2)
13. 合并k个升序链表
- 题目描述
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。 - 解题思路
分治,通过递归两两合并,其中会用到合并两个有序链表这个函数,在上一个题目排序链表中也用到了,因此这个模块函数要掌握好; - 代码
class Solution:def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:def merge(l1, l2):if not l1:return l2if not l2:return l1head = ListNode()cur = headnode1 = l1node2 = l2while node1 and node2:if node1.val < node2.val:cur.next = node1node1 = node1.nextelse:cur.next = node2node2 = node2.nextcur = cur.nextif node1:cur.next = node1if node2:cur.next = node2return head.nextn = len(lists)if n == 0:return Noneif len(lists) == 1:return lists[0]mid = n // 2head1 = self.mergeKLists(lists[: mid])head2 = self.mergeKLists(lists[mid :])return merge(head1, head2)
13 LRU
- 题目描述
请你设计并实现一个满足 LRU (最近最少使用) 缓存 约束的数据结构。
实现 LRUCache 类:
LRUCache(int capacity) 以 正整数 作为容量 capacity 初始化 LRU 缓存
int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
void put(int key, int value) 如果关键字 key 已经存在,则变更其数据值 value ;如果不存在,则向缓存中插入该组 key-value 。如果插入操作导致关键字数量超过 capacity ,则应该 逐出 最久未使用的关键字。
函数 get 和 put 必须以 O(1) 的平均时间复杂度运行。 - 解题思路
哈希表 + 双向链表。哈希表用于快速查找节点,双向链表用于存储使用情况,最近被使用的节点被放在双向链表的后端
时间复杂度: O(1), 空间复杂度:O(capacity)。
注意python的字典删除元素的方法是:pop(key[,default])
删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。 - 代码
class BiNode:def __init__(self, val=0, next=None, prev=None, key=None):self.val = valself.next = nextself.prev = prevself.key = keyclass LRUCache:def __init__(self, n):self.n = nself.dic = {}self.head = BiNode()self.tail = BiNode()self.head.next = self.tailself.tail.prev = self.headdef add_node_to_tail(self, node):self.tail.prev.next = nodenode.prev = self.tail.prevnode.next = self.tailself.tail.prev = nodedef rm_node(self, node):prev = node.prevnex = node.nextprev.next = nexnex.prev = prevdef get(self, key):if key in self.dic:self.rm_node(self.dic[key])self.add_node_to_tail(self.dic[key])return self.dic[key].valelse:return -1def put(self, key, value):if key in self.dic:self.dic[key].val = valueself.rm_node(self.dic[key])self.add_node_to_tail(self.dic[key])else:if len(self.dic) == self.n:to_delete = self.head.nextself.rm_node(to_delete)self.dic.pop(to_delete.key)new_node = BiNode()new_node.val = valuenew_node.key = keyself.dic[key] = new_nodeself.add_node_to_tail(new_node)# Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
总结
对于链表题目,主要的解题思路有:快慢指针、翻转链表(局部)、合并有序链表、查找中间位置的链表节点、将长链表分解切断成小的链表(分治)。
需要熟练掌握的模块:翻转链表、合并有序链表、查找中间位置的链表节点
查找中间位置的链表节点,使用快慢指针:
slow = head
fast = head.next
while fast and fast.next:slow = slow.nextfast = fast.next.next
相关文章:

Leetcode Hot100之链表
1.相交链表 解题思路 快慢指针:分别求出两个链表的长度n1和n2,在长度较长的那个链表上,快指针先走n2 - n1,慢指针再出发,最后能相遇则链表相交 时间复杂度O(mn),空间复杂度O(1)代码# Definition for singl…...

5.9k!一款清新好用的后台管理系统!【送源码】
今天给大家分享的开源项目是一个优雅清新后台管理系统——Soybean Admin。 简介 官方是这样介绍这个项目的: Soybean Admin 使用的是Vue3作为前端框架,TypeScript作为开发语言,同时还整合了NaiveUI组件库,使得系统具有高可用性和…...

Vue-cli搭建项目----基础版
什么是Vue-cli 全称:Vue command line interface 是一个用于快速搭建Vue.js项目的标准工具,他简化了Vue.js应用的创建和管理过程,通过命令工具帮助开发者快速生成,配置和管理Vue项目. 主要功能 同一的目录结构本地调试热部署单元测试集成打包上线 具体操作 第一步创建项目:…...
python之__call__函数介绍
Python 中的 __call__ 方法是一种特殊的方法,它允许对象像函数一样被调用。当你创建一个对象并使用括号 () 调用它时,Python 会自动调用这个对象的 __call__ 方法。 1. 基本用法 下面是一个简单的例子: class MyClass:def __init__(self, value):self.value valued…...
【AI】生成式AI服务器最低配置
【背景】 考虑数据安全,又想用AI赋能企业内部的日常工作,答案只有一个,本地部署。 UI采用open-web-ui,模型用Ollama管理,在局域网做成SAAS服务。要组一个服务器,提供部门内部最多30个的API并发。以下为反复…...

2.Android逆向协议-了解常用的逆向工具
免责声明:内容仅供学习参考,请合法利用知识,禁止进行违法犯罪活动! 内容参考于:微尘网校 上一个内容:1.Android逆向协议-环境搭建 常用的工具:AndroidKiller、jadx、JEB、IDA AndroidKiller…...

大数据------额外软件、插件及技术------Linux(完整知识点汇总)
Linxu 不同领域的主流操作系统 桌面操作系统 WindowsMAac OSLinux 服务器端操作系统 UNIX(付费)LinuxWindows Server(付费) 移动设备操作系统 Android(基于Linux开源)IOS(不开源) 嵌…...

iOS 其他应用的文件如何在分享中使用自己的应用打开
废话少说 一、第一步:先配置好plist文件 右击info.plist如下图文件打开 根据自己需要配置支持的文件类型,也可使用property List中配置,一样的 其他的文件可是参考文档:System-Declared Uniform Type Identifiers 可复制的代码&am…...

【编译原理必考大题】 推导构建语法树,写出语法树的短语,简单短语和句柄
写在最前 本文为编译原理重点考察大题之一,理论基础见专栏文章,0基础直接使用也可食用 文章目录 推导构造语法树1.语法树的概念2. 子树,短语,简单短语,句柄2.1 子树2.2 短语2.3 简单短语与句柄2.4 真题实战 推导构造语…...
redis服务介绍
redis 基础概念安装使用基础操作命令数据类型操作命令 管理和维护命令 基础概念 Remote Dictionary Server(Redis)远程字典服务器是完全开源免费的,用C语言编写的,遵守BSD开源协议,是一个高性能的(key/val…...

nodepad 中换行符、tab替换
1 nodepad 主要符号 换行符: \r\n(windows) tab: \t 2 展示符号 3 相互替换 tip:需要点击扩展 参考: https://blog.csdn.net/lijing742180/article/details/85174564...

常见的字符串函数(包含头文件string.h)和字符函数(2)
八. strstr函数 1.strstr的定义 char *strstr( const char *str1, const char *str2 ); ->1. strstr查找子串(str2)在字符串(str2)中第一次出现的位置,记录并返回该位置的指针,如果找不到,则返回NULL ->2. str1:查找字符…...

Python | Leetcode Python题解之第187题重复的DNA序列
题目: 题解: L 10 bin {A: 0, C: 1, G: 2, T: 3}class Solution:def findRepeatedDnaSequences(self, s: str) -> List[str]:n len(s)if n < L:return []ans []x 0for ch in s[:L - 1]:x (x << 2) | bin[ch]cnt defaultdict(int)for…...

SpringCloud分布式微服务链路追踪方案:Skywalking
一、引言 随着微服务架构的广泛应用,系统的复杂性也随之增加。在这种复杂的系统中,应用通常由多个相互独立的服务组成,每个服务可能分布在不同的主机上。微服务架构虽然提高了系统的灵活性和可扩展性,但也带来了新的挑战…...

首次线下联合亮相!灵途科技携手AEye、ATI亮相2024 EAC 易贸汽车产业大会
6月22日,2024 EAC 易贸汽车产业大会在苏州国际博览中心圆满落幕,泛自动驾驶领域光电感知专家灵途科技携手自适应高性能激光雷达解决方案全球领导者AEye公司(NASDAQ:LIDR)及光电器件规模化量产巨头Accelight Technologiesÿ…...

一文入门CMake
我们前几篇文章已经入门了gcc和Makefile,现在可以来玩玩CMake了。 CMake和Makefile是差不多的,基本上是可以相互替换使用的。CMAke可以生成Makefile,所以本质上我们还是用的Makefile,只不过用了CMake就不用再写Makefile了&#x…...
【LeetCode面试经典150题】117. 填充每个节点的下一个右侧节点指针 II
一、题目 117. 填充每个节点的下一个右侧节点指针 II - 力扣(LeetCode) 给定一个二叉树: struct Node {int val;Node *left;Node *right;Node *next; } 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个…...

RTDETR更换优化器——Lion
RTDETR更换Lion优化器 论文:https://arxiv.org/abs/2302.06675 代码:https://github.com/google/automl/blob/master/lion/lion_pytorch.py 简介: Lion优化器是一种基于梯度的优化算法,旨在提高梯度下降法在深度学习中的优化效果…...
Spring Boot中最佳实践:数据源配置详解
Spring Boot中最佳实践:数据源配置详解 大家好,我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿!今天我们将深入探讨在Spring Boot中如何进行最佳实践的数据源…...

第1章 物联网模式简介---独特要求和体系结构原则
物联网用例的独特要求 物联网用例往往在功耗、带宽、分析等方面具有非常独特的要求。此外,物联网实施的固有复杂性(一端的现场设备在计算上受到挑战,另一端的云容量几乎无限)迫使架构师做出艰难的架构决策和实施选择。可用实现技…...
【RockeMQ】第2节|RocketMQ快速实战以及核⼼概念详解(二)
升级Dledger高可用集群 一、主从架构的不足与Dledger的定位 主从架构缺陷 数据备份依赖Slave节点,但无自动故障转移能力,Master宕机后需人工切换,期间消息可能无法读取。Slave仅存储数据,无法主动升级为Master响应请求ÿ…...
大学生职业发展与就业创业指导教学评价
这里是引用 作为软工2203/2204班的学生,我们非常感谢您在《大学生职业发展与就业创业指导》课程中的悉心教导。这门课程对我们即将面临实习和就业的工科学生来说至关重要,而您认真负责的教学态度,让课程的每一部分都充满了实用价值。 尤其让我…...

【数据分析】R版IntelliGenes用于生物标志物发现的可解释机器学习
禁止商业或二改转载,仅供自学使用,侵权必究,如需截取部分内容请后台联系作者! 文章目录 介绍流程步骤1. 输入数据2. 特征选择3. 模型训练4. I-Genes 评分计算5. 输出结果 IntelliGenesR 安装包1. 特征选择2. 模型训练和评估3. I-Genes 评分计…...

Unsafe Fileupload篇补充-木马的详细教程与木马分享(中国蚁剑方式)
在之前的皮卡丘靶场第九期Unsafe Fileupload篇中我们学习了木马的原理并且学了一个简单的木马文件 本期内容是为了更好的为大家解释木马(服务器方面的)的原理,连接,以及各种木马及连接工具的分享 文件木马:https://w…...

保姆级教程:在无网络无显卡的Windows电脑的vscode本地部署deepseek
文章目录 1 前言2 部署流程2.1 准备工作2.2 Ollama2.2.1 使用有网络的电脑下载Ollama2.2.2 安装Ollama(有网络的电脑)2.2.3 安装Ollama(无网络的电脑)2.2.4 安装验证2.2.5 修改大模型安装位置2.2.6 下载Deepseek模型 2.3 将deepse…...

七、数据库的完整性
七、数据库的完整性 主要内容 7.1 数据库的完整性概述 7.2 实体完整性 7.3 参照完整性 7.4 用户定义的完整性 7.5 触发器 7.6 SQL Server中数据库完整性的实现 7.7 小结 7.1 数据库的完整性概述 数据库完整性的含义 正确性 指数据的合法性 有效性 指数据是否属于所定…...

Python训练营-Day26-函数专题1:函数定义与参数
题目1:计算圆的面积 任务: 编写一个名为 calculate_circle_area 的函数,该函数接收圆的半径 radius 作为参数,并返回圆的面积。圆的面积 π * radius (可以使用 math.pi 作为 π 的值)要求:函数接收一个位置参数 radi…...

算术操作符与类型转换:从基础到精通
目录 前言:从基础到实践——探索运算符与类型转换的奥秘 算术操作符超级详解 算术操作符:、-、*、/、% 赋值操作符:和复合赋值 单⽬操作符:、--、、- 前言:从基础到实践——探索运算符与类型转换的奥秘 在先前的文…...
FTXUI::Dom 模块
DOM 模块定义了分层的 FTXUI::Element 树,可用于构建复杂的终端界面,支持响应终端尺寸变化。 namespace ftxui {...// 定义文档 定义布局盒子 Element document vbox({// 设置文本 设置加粗 设置文本颜色text("The window") | bold | color(…...
Easy Excel
Easy Excel 一、依赖引入二、基本使用1. 定义实体类(导入/导出共用)2. 写 Excel3. 读 Excel 三、常用注解说明(完整列表)四、进阶:自定义转换器(Converter) 其它自定义转换器没生效 Easy Excel在…...