feat: Revised the book (#978)

* Sync recent changes to the revised Word.

* Revised the preface chapter

* Revised the introduction chapter

* Revised the computation complexity chapter

* Revised the chapter data structure

* Revised the chapter array and linked list

* Revised the chapter stack and queue

* Revised the chapter hashing

* Revised the chapter tree

* Revised the chapter heap

* Revised the chapter graph

* Revised the chapter searching

* Reivised the sorting chapter

* Revised the divide and conquer chapter

* Revised the chapter backtacking

* Revised the DP chapter

* Revised the greedy chapter

* Revised the appendix chapter

* Revised the preface chapter doubly

* Revised the figures
This commit is contained in:
Yudong Jin
2023-12-02 06:21:34 +08:00
committed by GitHub
parent b824d149cb
commit e720aa2d24
404 changed files with 1537 additions and 1558 deletions

View File

@ -17,7 +17,7 @@ def random_access(nums: list[int]) -> int:
# 请注意Python 的 list 是动态数组,可以直接扩展
# 为了方便学习,本函数将 list 看作长度不可变的数组
# 为了方便学习,本函数将 list 看作长度不可变的数组
def extend(nums: list[int], enlarge: int) -> list[int]:
"""扩展数组长度"""
# 初始化一个扩展长度后的数组
@ -34,12 +34,12 @@ def insert(nums: list[int], num: int, index: int):
# 把索引 index 以及之后的所有元素向后移动一位
for i in range(len(nums) - 1, index, -1):
nums[i] = nums[i - 1]
# 将 num 赋给 index 处元素
# 将 num 赋给 index 处元素
nums[index] = num
def remove(nums: list[int], index: int):
"""删除索引 index 处元素"""
"""删除索引 index 处元素"""
# 把索引 index 之后的所有元素向前移动一位
for i in range(index, len(nums) - 1):
nums[i] = nums[i + 1]

View File

@ -57,7 +57,7 @@ if __name__ == "__main__":
n2 = ListNode(2)
n3 = ListNode(5)
n4 = ListNode(4)
# 构建引用指向
# 构建节点之间的引用
n0.next = n1
n1.next = n2
n2.next = n3

View File

@ -22,7 +22,7 @@ if __name__ == "__main__":
nums.clear()
print("\n清空列表后 nums =", nums)
# 尾部添加元素
# 尾部添加元素
nums.append(1)
nums.append(3)
nums.append(2)
@ -30,7 +30,7 @@ if __name__ == "__main__":
nums.append(4)
print("\n添加元素后 nums =", nums)
# 中间插入元素
# 中间插入元素
nums.insert(3, 6)
print("\n在索引 3 处插入数字 6 ,得到 nums =", nums)

View File

@ -6,17 +6,17 @@ Author: Krahets (krahets@163.com)
class MyList:
"""列表类简易实现"""
"""列表类"""
def __init__(self):
"""构造方法"""
self._capacity: int = 10 # 列表容量
self._arr: list[int] = [0] * self._capacity # 数组(存储列表元素)
self._size: int = 0 # 列表长度(当前元素数量)
self._size: int = 0 # 列表长度(当前元素数量)
self._extend_ratio: int = 2 # 每次列表扩容的倍数
def size(self) -> int:
"""获取列表长度(当前元素数量)"""
"""获取列表长度(当前元素数量)"""
return self._size
def capacity(self) -> int:
@ -37,7 +37,7 @@ class MyList:
self._arr[index] = num
def add(self, num: int):
"""尾部添加元素"""
"""尾部添加元素"""
# 元素数量超出容量时,触发扩容机制
if self.size() == self.capacity():
self.extend_capacity()
@ -45,7 +45,7 @@ class MyList:
self._size += 1
def insert(self, num: int, index: int):
"""中间插入元素"""
"""中间插入元素"""
if index < 0 or index >= self._size:
raise IndexError("索引越界")
# 元素数量超出容量时,触发扩容机制
@ -87,7 +87,7 @@ class MyList:
if __name__ == "__main__":
# 初始化列表
nums = MyList()
# 尾部添加元素
# 尾部添加元素
nums.add(1)
nums.add(3)
nums.add(2)
@ -95,7 +95,7 @@ if __name__ == "__main__":
nums.add(4)
print(f"列表 nums = {nums.to_array()} ,容量 = {nums.capacity()} ,长度 = {nums.size()}")
# 中间插入元素
# 中间插入元素
nums.insert(6, index=3)
print("在索引 3 处插入数字 6 ,得到 nums =", nums.to_array())

View File

@ -24,7 +24,7 @@ def backtrack(
# 计算该格子对应的主对角线和副对角线
diag1 = row - col + n - 1
diag2 = row + col
# 剪枝:不允许该格子所在列、主对角线、副对角线存在皇后
# 剪枝:不允许该格子所在列、主对角线、副对角线存在皇后
if not cols[col] and not diags1[diag1] and not diags2[diag2]:
# 尝试:将皇后放置在该格子
state[row][col] = "Q"
@ -41,8 +41,8 @@ def n_queens(n: int) -> list[list[list[str]]]:
# 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
state = [["#" for _ in range(n)] for _ in range(n)]
cols = [False] * n # 记录列是否有皇后
diags1 = [False] * (2 * n - 1) # 记录主对角线是否有皇后
diags2 = [False] * (2 * n - 1) # 记录副对角线是否有皇后
diags1 = [False] * (2 * n - 1) # 记录主对角线是否有皇后
diags2 = [False] * (2 * n - 1) # 记录副对角线是否有皇后
res = []
backtrack(0, n, state, res, cols, diags1, diags2)

View File

@ -29,7 +29,7 @@ def while_loop_ii(n: int) -> int:
"""while 循环(两次更新)"""
res = 0
i = 1 # 初始化条件变量
# 循环求和 1, 4, ...
# 循环求和 1, 4, 10, ...
while i <= n:
res += i
# 更新条件变量

View File

@ -14,7 +14,7 @@ def move(src: list[int], tar: list[int]):
def dfs(i: int, src: list[int], buf: list[int], tar: list[int]):
"""求解汉诺塔问题 f(i)"""
"""求解汉诺塔问题 f(i)"""
# 若 src 只剩下一个圆盘,则直接将其移到 tar
if i == 1:
move(src, tar)
@ -28,7 +28,7 @@ def dfs(i: int, src: list[int], buf: list[int], tar: list[int]):
def solve_hanota(A: list[int], B: list[int], C: list[int]):
"""求解汉诺塔"""
"""求解汉诺塔问题"""
n = len(A)
# 将 A 顶部 n 个圆盘借助 B 移到 C
dfs(n, A, B, C)

View File

@ -22,7 +22,7 @@ def backtrack(choices: list[int], state: int, n: int, res: list[int]) -> int:
def climbing_stairs_backtrack(n: int) -> int:
"""爬楼梯:回溯"""
choices = [1, 2] # 可选择向上爬 1 或 2 阶
choices = [1, 2] # 可选择向上爬 1 或 2 阶
state = 0 # 从第 0 阶开始爬
res = [0] # 使用 res[0] 记录方案数量
backtrack(choices, state, n, res)

View File

@ -14,7 +14,7 @@ def coin_change_dp(coins: list[int], amt: int) -> int:
# 状态转移:首行首列
for a in range(1, amt + 1):
dp[0][a] = MAX
# 状态转移:其余行列
# 状态转移:其余行
for i in range(1, n + 1):
for a in range(1, amt + 1):
if coins[i - 1] > a:

View File

@ -62,7 +62,7 @@ def edit_distance_dp(s: str, t: str) -> int:
dp[i][0] = i
for j in range(1, m + 1):
dp[0][j] = j
# 状态转移:其余行列
# 状态转移:其余行
for i in range(1, n + 1):
for j in range(1, m + 1):
if s[i - 1] == t[j - 1]:

View File

@ -7,10 +7,10 @@ Author: Krahets (krahets@163.com)
def knapsack_dfs(wgt: list[int], val: list[int], i: int, c: int) -> int:
"""0-1 背包:暴力搜索"""
# 若已选完所有物品或背包无容量,则返回价值 0
# 若已选完所有物品或背包无剩余容量,则返回价值 0
if i == 0 or c == 0:
return 0
# 若超过背包容量,则只能不放入背包
# 若超过背包容量,则只能选择不放入背包
if wgt[i - 1] > c:
return knapsack_dfs(wgt, val, i - 1, c)
# 计算不放入和放入物品 i 的最大价值
@ -24,13 +24,13 @@ def knapsack_dfs_mem(
wgt: list[int], val: list[int], mem: list[list[int]], i: int, c: int
) -> int:
"""0-1 背包:记忆化搜索"""
# 若已选完所有物品或背包无容量,则返回价值 0
# 若已选完所有物品或背包无剩余容量,则返回价值 0
if i == 0 or c == 0:
return 0
# 若已有记录,则直接返回
if mem[i][c] != -1:
return mem[i][c]
# 若超过背包容量,则只能不放入背包
# 若超过背包容量,则只能选择不放入背包
if wgt[i - 1] > c:
return knapsack_dfs_mem(wgt, val, mem, i - 1, c)
# 计算不放入和放入物品 i 的最大价值

View File

@ -55,7 +55,7 @@ def min_path_sum_dp(grid: list[list[int]]) -> int:
# 状态转移:首列
for i in range(1, n):
dp[i][0] = dp[i - 1][0] + grid[i][0]
# 状态转移:其余行列
# 状态转移:其余行
for i in range(1, n):
for j in range(1, m):
dp[i][j] = min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j]

View File

@ -16,7 +16,7 @@ class GraphAdjList:
def __init__(self, edges: list[list[Vertex]]):
"""构造方法"""
# 邻接表key: 顶点value该顶点的所有邻接顶点
# 邻接表key顶点value该顶点的所有邻接顶点
self.adj_list = dict[Vertex, list[Vertex]]()
# 添加所有顶点和边
for edge in edges:

View File

@ -62,7 +62,7 @@ class GraphAdjMat:
# 索引越界与相等处理
if i < 0 or j < 0 or i >= self.size() or j >= self.size() or i == j:
raise IndexError()
# 在无向图中,邻接矩阵沿主对角线对称,即满足 (i, j) == (j, i)
# 在无向图中,邻接矩阵关于主对角线对称,即满足 (i, j) == (j, i)
self.adj_mat[i][j] = 1
self.adj_mat[j][i] = 1

View File

@ -29,7 +29,7 @@ def graph_bfs(graph: GraphAdjList, start_vet: Vertex) -> list[Vertex]:
# 遍历该顶点的所有邻接顶点
for adj_vet in graph.adj_list[vet]:
if adj_vet in visited:
continue # 跳过已被访问的顶点
continue # 跳过已被访问的顶点
que.append(adj_vet) # 只入队未访问的顶点
visited.add(adj_vet) # 标记该顶点已被访问
# 返回顶点遍历序列

View File

@ -19,7 +19,7 @@ def dfs(graph: GraphAdjList, visited: set[Vertex], res: list[Vertex], vet: Verte
# 遍历该顶点的所有邻接顶点
for adjVet in graph.adj_list[vet]:
if adjVet in visited:
continue # 跳过已被访问的顶点
continue # 跳过已被访问的顶点
# 递归访问邻接顶点
dfs(graph, visited, res, adjVet)

View File

@ -14,7 +14,7 @@ class Pair:
class ArrayHashMap:
"""基于数组简易实现的哈希表"""
"""基于数组实现的哈希表"""
def __init__(self):
"""构造方法"""

View File

@ -75,7 +75,7 @@ class MaxHeap:
# 判空处理
if self.is_empty():
raise IndexError("堆为空")
# 交换根节点与最右叶节点(交换首元素与尾元素)
# 交换根节点与最右叶节点(交换首元素与尾元素)
self.swap(0, self.size() - 1)
# 删除节点
val = self.max_heap.pop()

View File

@ -23,8 +23,8 @@ def binary_search(nums: list[int], target: int) -> int:
def binary_search_lcro(nums: list[int], target: int) -> int:
"""二分查找(左闭右开)"""
# 初始化左闭右开 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
"""二分查找(左闭右开区间"""
# 初始化左闭右开区间 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
i, j = 0, len(nums)
# 循环,当搜索区间为空时跳出(当 i = j 时为空)
while i < j:
@ -47,6 +47,6 @@ if __name__ == "__main__":
index: int = binary_search(nums, target)
print("目标元素 6 的索引 = ", index)
# 二分查找(左闭右开)
# 二分查找(左闭右开区间
index: int = binary_search_lcro(nums, target)
print("目标元素 6 的索引 = ", index)

View File

@ -7,7 +7,7 @@ Author: Krahets (krahets@163.com)
def two_sum_brute_force(nums: list[int], target: int) -> list[int]:
"""方法一:暴力枚举"""
# 两层循环,时间复杂度 O(n^2)
# 两层循环,时间复杂度 O(n^2)
for i in range(len(nums) - 1):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
@ -17,9 +17,9 @@ def two_sum_brute_force(nums: list[int], target: int) -> list[int]:
def two_sum_hash_table(nums: list[int], target: int) -> list[int]:
"""方法二:辅助哈希表"""
# 辅助哈希表,空间复杂度 O(n)
# 辅助哈希表,空间复杂度 O(n)
dic = {}
# 单层循环,时间复杂度 O(n)
# 单层循环,时间复杂度 O(n)
for i in range(len(nums)):
if target - nums[i] in dic:
return [dic[target - nums[i]], i]

View File

@ -12,7 +12,7 @@ def bucket_sort(nums: list[float]):
buckets = [[] for _ in range(k)]
# 1. 将数组元素分配到各个桶中
for num in nums:
# 输入数据范围 [0, 1),使用 num * k 映射到索引范围 [0, k-1]
# 输入数据范围 [0, 1),使用 num * k 映射到索引范围 [0, k-1]
i = int(num * k)
# 将 num 添加进桶 i
buckets[i].append(num)

View File

@ -32,7 +32,7 @@ def heap_sort(nums: list[int]):
sift_down(nums, len(nums), i)
# 从堆中提取最大元素,循环 n-1 轮
for i in range(len(nums) - 1, 0, -1):
# 交换根节点与最右叶节点(交换首元素与尾元素)
# 交换根节点与最右叶节点(交换首元素与尾元素)
nums[0], nums[i] = nums[i], nums[0]
# 以根节点为起点,从顶至底进行堆化
sift_down(nums, i, 0)

View File

@ -10,7 +10,7 @@ class QuickSort:
def partition(self, nums: list[int], left: int, right: int) -> int:
"""哨兵划分"""
# 以 nums[left] 为基准数
# 以 nums[left] 为基准数
i, j = left, right
while i < j:
while i < j and nums[j] >= nums[left]:
@ -50,11 +50,11 @@ class QuickSortMedian:
def partition(self, nums: list[int], left: int, right: int) -> int:
"""哨兵划分(三数取中值)"""
# 以 nums[left] 为基准数
# 以 nums[left] 为基准数
med = self.median_three(nums, left, (left + right) // 2, right)
# 将中位数交换至数组最左端
nums[left], nums[med] = nums[med], nums[left]
# 以 nums[left] 为基准数
# 以 nums[left] 为基准数
i, j = left, right
while i < j:
while i < j and nums[j] >= nums[left]:
@ -84,7 +84,7 @@ class QuickSortTailCall:
def partition(self, nums: list[int], left: int, right: int) -> int:
"""哨兵划分"""
# 以 nums[left] 为基准数
# 以 nums[left] 为基准数
i, j = left, right
while i < j:
while i < j and nums[j] >= nums[left]:
@ -103,7 +103,7 @@ class QuickSortTailCall:
while left < right:
# 哨兵划分操作
pivot = self.partition(nums, left, right)
# 对两个子数组中较短的那个执行快
# 对两个子数组中较短的那个执行快速排序
if pivot - left < right - pivot:
self.quick_sort(nums, left, pivot - 1) # 递归排序左子数组
left = pivot + 1 # 剩余未排序区间为 [pivot + 1, right]

View File

@ -13,7 +13,7 @@ def digit(num: int, exp: int) -> int:
def counting_sort_digit(nums: list[int], exp: int):
"""计数排序(根据 nums 第 k 位排序)"""
# 十进制的位范围为 0~9 ,因此需要长度为 10 的桶
# 十进制的位范围为 0~9 ,因此需要长度为 10 的桶数组
counter = [0] * 10
n = len(nums)
# 统计 0~9 各数字的出现次数

View File

@ -35,7 +35,7 @@ class LinkedListDeque:
def push(self, num: int, is_front: bool):
"""入队操作"""
node = ListNode(num)
# 若链表为空,则令 front, rear 都指向 node
# 若链表为空,则令 front rear 都指向 node
if self.is_empty():
self._front = self._rear = node
# 队首入队操作

View File

@ -20,7 +20,7 @@ if __name__ == "__main__":
n3 = TreeNode(val=3)
n4 = TreeNode(val=4)
n5 = TreeNode(val=5)
# 构建引用指向(即指针)
# 构建节点之间的引用(指针)
n1.left = n2
n1.right = n3
n2.left = n4