mirror of
https://github.com/krahets/hello-algo.git
synced 2025-11-02 12:58:42 +08:00
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:
@ -35,11 +35,11 @@ fn insert(nums: &mut Vec<i32>, num: i32, index: usize) {
|
||||
for i in (index + 1..nums.len()).rev() {
|
||||
nums[i] = nums[i - 1];
|
||||
}
|
||||
// 将 num 赋给 index 处元素
|
||||
// 将 num 赋给 index 处的元素
|
||||
nums[index] = num;
|
||||
}
|
||||
|
||||
/* 删除索引 index 处元素 */
|
||||
/* 删除索引 index 处的元素 */
|
||||
fn remove(nums: &mut Vec<i32>, index: usize) {
|
||||
// 把索引 index 之后的所有元素向前移动一位
|
||||
for i in index..nums.len() - 1 {
|
||||
|
||||
@ -57,7 +57,7 @@ fn main() {
|
||||
let n2 = ListNode::new(2);
|
||||
let n3 = ListNode::new(5);
|
||||
let n4 = ListNode::new(4);
|
||||
// 构建引用指向
|
||||
// 构建节点之间的引用
|
||||
n0.borrow_mut().next = Some(n1.clone());
|
||||
n1.borrow_mut().next = Some(n2.clone());
|
||||
n2.borrow_mut().next = Some(n3.clone());
|
||||
|
||||
@ -27,7 +27,7 @@ fn main() {
|
||||
print!("\n清空列表后 nums = ");
|
||||
print_util::print_array(&nums);
|
||||
|
||||
// 尾部添加元素
|
||||
// 在尾部添加元素
|
||||
nums.push(1);
|
||||
nums.push(3);
|
||||
nums.push(2);
|
||||
@ -36,7 +36,7 @@ fn main() {
|
||||
print!("\n添加元素后 nums = ");
|
||||
print_util::print_array(&nums);
|
||||
|
||||
// 中间插入元素
|
||||
// 在中间插入元素
|
||||
nums.insert(3, 6);
|
||||
print!("\n在索引 3 处插入数字 6 ,得到 nums = ");
|
||||
print_util::print_array(&nums);
|
||||
|
||||
@ -6,12 +6,12 @@
|
||||
|
||||
include!("../include/include.rs");
|
||||
|
||||
/* 列表类简易实现 */
|
||||
/* 列表类 */
|
||||
#[allow(dead_code)]
|
||||
struct MyList {
|
||||
arr: Vec<i32>, // 数组(存储列表元素)
|
||||
capacity: usize, // 列表容量
|
||||
size: usize, // 列表长度(即当前元素数量)
|
||||
size: usize, // 列表长度(当前元素数量)
|
||||
extend_ratio: usize, // 每次列表扩容的倍数
|
||||
}
|
||||
|
||||
@ -29,7 +29,7 @@ impl MyList {
|
||||
}
|
||||
}
|
||||
|
||||
/* 获取列表长度(即当前元素数量)*/
|
||||
/* 获取列表长度(当前元素数量)*/
|
||||
pub fn size(&self) -> usize {
|
||||
return self.size;
|
||||
}
|
||||
@ -52,7 +52,7 @@ impl MyList {
|
||||
self.arr[index] = num;
|
||||
}
|
||||
|
||||
/* 尾部添加元素 */
|
||||
/* 在尾部添加元素 */
|
||||
pub fn add(&mut self, num: i32) {
|
||||
// 元素数量超出容量时,触发扩容机制
|
||||
if self.size == self.capacity() {
|
||||
@ -63,7 +63,7 @@ impl MyList {
|
||||
self.size += 1;
|
||||
}
|
||||
|
||||
/* 中间插入元素 */
|
||||
/* 在中间插入元素 */
|
||||
pub fn insert(&mut self, index: usize, num: i32) {
|
||||
if index >= self.size() {panic!("索引越界")};
|
||||
// 元素数量超出容量时,触发扩容机制
|
||||
@ -117,7 +117,7 @@ impl MyList {
|
||||
fn main() {
|
||||
/* 初始化列表 */
|
||||
let mut nums = MyList::new(10);
|
||||
/* 尾部添加元素 */
|
||||
/* 在尾部添加元素 */
|
||||
nums.add(1);
|
||||
nums.add(3);
|
||||
nums.add(2);
|
||||
@ -127,7 +127,7 @@ fn main() {
|
||||
print_util::print_array(&nums.to_array());
|
||||
print!(" ,容量 = {} ,长度 = {}", nums.capacity(), nums.size());
|
||||
|
||||
/* 中间插入元素 */
|
||||
/* 在中间插入元素 */
|
||||
nums.insert(3, 6);
|
||||
print!("\n在索引 3 处插入数字 6 ,得到 nums = ");
|
||||
print_util::print_array(&nums.to_array());
|
||||
|
||||
@ -21,7 +21,7 @@ fn backtrack(row: usize, n: usize, state: &mut Vec<Vec<String>>, res: &mut Vec<V
|
||||
// 计算该格子对应的主对角线和副对角线
|
||||
let diag1 = row + n - 1 - col;
|
||||
let diag2 = row + col;
|
||||
// 剪枝:不允许该格子所在列、主对角线、副对角线存在皇后
|
||||
// 剪枝:不允许该格子所在列、主对角线、副对角线上存在皇后
|
||||
if !cols[col] && !diags1[diag1] && !diags2[diag2] {
|
||||
// 尝试:将皇后放置在该格子
|
||||
state.get_mut(row).unwrap()[col] = "Q".into();
|
||||
@ -47,8 +47,8 @@ fn n_queens(n: usize) -> Vec<Vec<Vec<String>>> {
|
||||
state.push(row);
|
||||
}
|
||||
let mut cols = vec![false; n]; // 记录列是否有皇后
|
||||
let mut diags1 = vec![false; 2 * n - 1]; // 记录主对角线是否有皇后
|
||||
let mut diags2 = vec![false; 2 * n - 1]; // 记录副对角线是否有皇后
|
||||
let mut diags1 = vec![false; 2 * n - 1]; // 记录主对角线上是否有皇后
|
||||
let mut diags2 = vec![false; 2 * n - 1]; // 记录副对角线上是否有皇后
|
||||
let mut res: Vec<Vec<Vec<String>>> = Vec::new();
|
||||
|
||||
backtrack(0, n, &mut state, &mut res, &mut cols, &mut diags1, &mut diags2);
|
||||
|
||||
@ -31,7 +31,7 @@ fn while_loop(n: i32) -> i32 {
|
||||
fn while_loop_ii(n: i32) -> i32 {
|
||||
let mut res = 0;
|
||||
let mut i = 1; // 初始化条件变量
|
||||
// 循环求和 1, 4, ...
|
||||
// 循环求和 1, 4, 10, ...
|
||||
while i <= n {
|
||||
res += i;
|
||||
// 更新条件变量
|
||||
|
||||
@ -14,7 +14,7 @@ fn move_pan(src: &mut Vec<i32>, tar: &mut Vec<i32>) {
|
||||
tar.push(pan);
|
||||
}
|
||||
|
||||
/* 求解汉诺塔:问题 f(i) */
|
||||
/* 求解汉诺塔问题 f(i) */
|
||||
fn dfs(i: i32, src: &mut Vec<i32>, buf: &mut Vec<i32>, tar: &mut Vec<i32>) {
|
||||
// 若 src 只剩下一个圆盘,则直接将其移到 tar
|
||||
if i == 1 {
|
||||
@ -29,7 +29,7 @@ fn dfs(i: i32, src: &mut Vec<i32>, buf: &mut Vec<i32>, tar: &mut Vec<i32>) {
|
||||
dfs(i - 1, buf, src, tar);
|
||||
}
|
||||
|
||||
/* 求解汉诺塔 */
|
||||
/* 求解汉诺塔问题 */
|
||||
fn solve_hanota(A: &mut Vec<i32>, B: &mut Vec<i32>, C: &mut Vec<i32>) {
|
||||
let n = A.len() as i32;
|
||||
// 将 A 顶部 n 个圆盘借助 B 移到 C
|
||||
|
||||
@ -20,7 +20,7 @@ fn backtrack(choices: &[i32], state: i32, n: i32, res: &mut [i32]) {
|
||||
|
||||
/* 爬楼梯:回溯 */
|
||||
fn climbing_stairs_backtrack(n: usize) -> i32 {
|
||||
let choices = vec![ 1, 2 ]; // 可选择向上爬 1 或 2 阶
|
||||
let choices = vec![ 1, 2 ]; // 可选择向上爬 1 阶或 2 阶
|
||||
let state = 0; // 从第 0 阶开始爬
|
||||
let mut res = Vec::new();
|
||||
res.push(0); // 使用 res[0] 记录方案数量
|
||||
|
||||
@ -14,7 +14,7 @@ fn coin_change_dp(coins: &[i32], amt: usize) -> i32 {
|
||||
for a in 1..= amt {
|
||||
dp[0][a] = max;
|
||||
}
|
||||
// 状态转移:其余行列
|
||||
// 状态转移:其余行和列
|
||||
for i in 1..=n {
|
||||
for a in 1..=amt {
|
||||
if coins[i - 1] > a as i32 {
|
||||
|
||||
@ -58,7 +58,7 @@ fn edit_distance_dp(s: &str, t: &str) -> i32 {
|
||||
for j in 1..m {
|
||||
dp[0][j] = j as i32;
|
||||
}
|
||||
// 状态转移:其余行列
|
||||
// 状态转移:其余行和列
|
||||
for i in 1..=n {
|
||||
for j in 1..=m {
|
||||
if s.chars().nth(i - 1) == t.chars().nth(j - 1) {
|
||||
|
||||
@ -6,11 +6,11 @@
|
||||
|
||||
/* 0-1 背包:暴力搜索 */
|
||||
fn knapsack_dfs(wgt: &[i32], val: &[i32], i: usize, c: usize) -> i32 {
|
||||
// 若已选完所有物品或背包无容量,则返回价值 0
|
||||
// 若已选完所有物品或背包无剩余容量,则返回价值 0
|
||||
if i == 0 || c == 0 {
|
||||
return 0;
|
||||
}
|
||||
// 若超过背包容量,则只能不放入背包
|
||||
// 若超过背包容量,则只能选择不放入背包
|
||||
if wgt[i - 1] > c as i32 {
|
||||
return knapsack_dfs(wgt, val, i - 1, c);
|
||||
}
|
||||
@ -23,7 +23,7 @@ fn knapsack_dfs(wgt: &[i32], val: &[i32], i: usize, c: usize) -> i32 {
|
||||
|
||||
/* 0-1 背包:记忆化搜索 */
|
||||
fn knapsack_dfs_mem(wgt: &[i32], val: &[i32], mem: &mut Vec<Vec<i32>>, i: usize, c: usize) -> i32 {
|
||||
// 若已选完所有物品或背包无容量,则返回价值 0
|
||||
// 若已选完所有物品或背包无剩余容量,则返回价值 0
|
||||
if i == 0 || c == 0 {
|
||||
return 0;
|
||||
}
|
||||
@ -31,7 +31,7 @@ fn knapsack_dfs_mem(wgt: &[i32], val: &[i32], mem: &mut Vec<Vec<i32>>, i: usize,
|
||||
if mem[i][c] != -1 {
|
||||
return mem[i][c];
|
||||
}
|
||||
// 若超过背包容量,则只能不放入背包
|
||||
// 若超过背包容量,则只能选择不放入背包
|
||||
if wgt[i - 1] > c as i32 {
|
||||
return knapsack_dfs_mem(wgt, val, mem, i - 1, c);
|
||||
}
|
||||
|
||||
@ -57,7 +57,7 @@ fn min_path_sum_dp(grid: &Vec<Vec<i32>>) -> i32 {
|
||||
for i in 1..n {
|
||||
dp[i][0] = dp[i - 1][0] + grid[i][0];
|
||||
}
|
||||
// 状态转移:其余行列
|
||||
// 状态转移:其余行和列
|
||||
for i in 1..n {
|
||||
for j in 1..m {
|
||||
dp[i][j] = std::cmp::min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j];
|
||||
|
||||
@ -10,7 +10,7 @@ use std::collections::HashMap;
|
||||
|
||||
/* 基于邻接表实现的无向图类型 */
|
||||
pub struct GraphAdjList {
|
||||
// 邻接表,key: 顶点,value:该顶点的所有邻接顶点
|
||||
// 邻接表,key:顶点,value:该顶点的所有邻接顶点
|
||||
pub adj_list: HashMap<Vertex, Vec<Vertex>>,
|
||||
}
|
||||
|
||||
|
||||
@ -72,7 +72,7 @@ impl GraphAdjMat {
|
||||
if i >= self.size() || j >= self.size() || i == j {
|
||||
panic!("index error")
|
||||
}
|
||||
// 在无向图中,邻接矩阵沿主对角线对称,即满足 (i, j) == (j, i)
|
||||
// 在无向图中,邻接矩阵关于主对角线对称,即满足 (i, j) == (j, i)
|
||||
self.adj_mat[i][j] = 1;
|
||||
self.adj_mat[j][i] = 1;
|
||||
}
|
||||
|
||||
@ -29,7 +29,7 @@ fn graph_bfs(graph: GraphAdjList, start_vet: Vertex) -> Vec<Vertex> {
|
||||
if let Some(adj_vets) = graph.adj_list.get(&vet) {
|
||||
for &adj_vet in adj_vets {
|
||||
if visited.contains(&adj_vet) {
|
||||
continue; // 跳过已被访问过的顶点
|
||||
continue; // 跳过已被访问的顶点
|
||||
}
|
||||
que.push_back(adj_vet); // 只入队未访问的顶点
|
||||
visited.insert(adj_vet); // 标记该顶点已被访问
|
||||
|
||||
@ -18,7 +18,7 @@ fn dfs(graph: &GraphAdjList, visited: &mut HashSet<Vertex>, res: &mut Vec<Vertex
|
||||
if let Some(adj_vets) = graph.adj_list.get(&vet) {
|
||||
for &adj_vet in adj_vets {
|
||||
if visited.contains(&adj_vet) {
|
||||
continue; // 跳过已被访问过的顶点
|
||||
continue; // 跳过已被访问的顶点
|
||||
}
|
||||
// 递归访问邻接顶点
|
||||
dfs(graph, visited, res, adj_vet);
|
||||
|
||||
@ -10,7 +10,7 @@ pub struct Pair {
|
||||
pub key: i32,
|
||||
pub val: String,
|
||||
}
|
||||
/* 基于数组简易实现的哈希表 */
|
||||
/* 基于数组实现的哈希表 */
|
||||
pub struct ArrayHashMap {
|
||||
buckets: Vec<Option<Pair>>
|
||||
}
|
||||
|
||||
@ -93,7 +93,7 @@ impl MaxHeap {
|
||||
if self.is_empty() {
|
||||
panic!("index out of bounds");
|
||||
}
|
||||
// 交换根节点与最右叶节点(即交换首元素与尾元素)
|
||||
// 交换根节点与最右叶节点(交换首元素与尾元素)
|
||||
self.swap(0, self.size() - 1);
|
||||
// 删除节点
|
||||
let val = self.max_heap.remove(self.size() - 1);
|
||||
|
||||
@ -24,9 +24,9 @@ fn binary_search(nums: &[i32], target: i32) -> i32 {
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* 二分查找(左闭右开) */
|
||||
/* 二分查找(左闭右开区间) */
|
||||
fn binary_search_lcro(nums: &[i32], target: i32) -> i32 {
|
||||
// 初始化左闭右开 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
|
||||
// 初始化左闭右开区间 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
|
||||
let mut i = 0;
|
||||
let mut j = nums.len() as i32;
|
||||
// 循环,当搜索区间为空时跳出(当 i = j 时为空)
|
||||
@ -53,7 +53,7 @@ pub fn main() {
|
||||
let mut index = binary_search(&nums, target);
|
||||
println!("目标元素 6 的索引 = {index}");
|
||||
|
||||
// 二分查找(左闭右开)
|
||||
// 二分查找(左闭右开区间)
|
||||
index = binary_search_lcro(&nums, target);
|
||||
println!("目标元素 6 的索引 = {index}");
|
||||
}
|
||||
|
||||
@ -11,7 +11,7 @@ use std::collections::HashMap;
|
||||
/* 方法一:暴力枚举 */
|
||||
pub fn two_sum_brute_force(nums: &Vec<i32>, target: i32) -> Option<Vec<i32>> {
|
||||
let size = nums.len();
|
||||
// 两层循环,时间复杂度 O(n^2)
|
||||
// 两层循环,时间复杂度为 O(n^2)
|
||||
for i in 0..size - 1 {
|
||||
for j in i + 1..size {
|
||||
if nums[i] + nums[j] == target {
|
||||
@ -24,9 +24,9 @@ pub fn two_sum_brute_force(nums: &Vec<i32>, target: i32) -> Option<Vec<i32>> {
|
||||
|
||||
/* 方法二:辅助哈希表 */
|
||||
pub fn two_sum_hash_table(nums: &Vec<i32>, target: i32) -> Option<Vec<i32>> {
|
||||
// 辅助哈希表,空间复杂度 O(n)
|
||||
// 辅助哈希表,空间复杂度为 O(n)
|
||||
let mut dic = HashMap::new();
|
||||
// 单层循环,时间复杂度 O(n)
|
||||
// 单层循环,时间复杂度为 O(n)
|
||||
for (i, num) in nums.iter().enumerate() {
|
||||
match dic.get(&(target - num)) {
|
||||
Some(v) => return Some(vec![*v as i32, i as i32]),
|
||||
|
||||
@ -13,7 +13,7 @@ fn bucket_sort(nums: &mut [f64]) {
|
||||
let mut buckets = vec![vec![]; k];
|
||||
// 1. 将数组元素分配到各个桶中
|
||||
for &mut num in &mut *nums {
|
||||
// 输入数据范围 [0, 1),使用 num * k 映射到索引范围 [0, k-1]
|
||||
// 输入数据范围为 [0, 1),使用 num * k 映射到索引范围 [0, k-1]
|
||||
let i = (num * k as f64) as usize;
|
||||
// 将 num 添加进桶 i
|
||||
buckets[i].push(num);
|
||||
|
||||
@ -40,7 +40,7 @@ fn heap_sort(nums: &mut [i32]) {
|
||||
}
|
||||
// 从堆中提取最大元素,循环 n-1 轮
|
||||
for i in (1..=nums.len() - 1).rev() {
|
||||
// 交换根节点与最右叶节点(即交换首元素与尾元素)
|
||||
// 交换根节点与最右叶节点(交换首元素与尾元素)
|
||||
let tmp = nums[0];
|
||||
nums[0] = nums[i];
|
||||
nums[i] = tmp;
|
||||
|
||||
@ -11,7 +11,7 @@ struct QuickSort;
|
||||
impl QuickSort {
|
||||
/* 哨兵划分 */
|
||||
fn partition(nums: &mut [i32], left: usize, right: usize) -> usize {
|
||||
// 以 nums[left] 作为基准数
|
||||
// 以 nums[left] 为基准数
|
||||
let (mut i, mut j) = (left, right);
|
||||
while i < j {
|
||||
while i < j && nums[j] >= nums[left] {
|
||||
@ -62,7 +62,7 @@ impl QuickSortMedian {
|
||||
let med = Self::median_three(nums, left, (left + right) / 2, right);
|
||||
// 将中位数交换至数组最左端
|
||||
nums.swap(left, med);
|
||||
// 以 nums[left] 作为基准数
|
||||
// 以 nums[left] 为基准数
|
||||
let (mut i, mut j) = (left, right);
|
||||
while i < j {
|
||||
while i < j && nums[j] >= nums[left] {
|
||||
@ -97,7 +97,7 @@ struct QuickSortTailCall;
|
||||
impl QuickSortTailCall {
|
||||
/* 哨兵划分 */
|
||||
fn partition(nums: &mut [i32], left: usize, right: usize) -> usize {
|
||||
// 以 nums[left] 作为基准数
|
||||
// 以 nums[left] 为基准数
|
||||
let (mut i, mut j) = (left, right);
|
||||
while i < j {
|
||||
while i < j && nums[j] >= nums[left] {
|
||||
@ -118,7 +118,7 @@ impl QuickSortTailCall {
|
||||
while left < right {
|
||||
// 哨兵划分操作
|
||||
let pivot = Self::partition(nums, left as usize, right as usize) as i32;
|
||||
// 对两个子数组中较短的那个执行快排
|
||||
// 对两个子数组中较短的那个执行快速排序
|
||||
if pivot - left < right - pivot {
|
||||
Self::quick_sort(left, pivot - 1, nums); // 递归排序左子数组
|
||||
left = pivot + 1; // 剩余未排序区间为 [pivot + 1, right]
|
||||
|
||||
@ -14,7 +14,7 @@ fn digit(num: i32, exp: i32) -> usize {
|
||||
|
||||
/* 计数排序(根据 nums 第 k 位排序) */
|
||||
fn counting_sort_digit(nums: &mut [i32], exp: i32) {
|
||||
// 十进制的位范围为 0~9 ,因此需要长度为 10 的桶
|
||||
// 十进制的位范围为 0~9 ,因此需要长度为 10 的桶数组
|
||||
let mut counter = [0; 10];
|
||||
let n = nums.len();
|
||||
// 统计 0~9 各数字的出现次数
|
||||
|
||||
@ -59,7 +59,7 @@ impl<T: Copy> LinkedListDeque<T> {
|
||||
// 队首入队操作
|
||||
if is_front {
|
||||
match self.front.take() {
|
||||
// 若链表为空,则令 front, rear 都指向 node
|
||||
// 若链表为空,则令 front 和 rear 都指向 node
|
||||
None => {
|
||||
self.rear = Some(node.clone());
|
||||
self.front = Some(node);
|
||||
@ -75,7 +75,7 @@ impl<T: Copy> LinkedListDeque<T> {
|
||||
// 队尾入队操作
|
||||
else {
|
||||
match self.rear.take() {
|
||||
// 若链表为空,则令 front, rear 都指向 node
|
||||
// 若链表为空,则令 front 和 rear 都指向 node
|
||||
None => {
|
||||
self.front = Some(node.clone());
|
||||
self.rear = Some(node);
|
||||
|
||||
@ -17,7 +17,7 @@ fn main() {
|
||||
let n3 = TreeNode::new(3);
|
||||
let n4 = TreeNode::new(4);
|
||||
let n5 = TreeNode::new(5);
|
||||
// 构建引用指向(即指针)
|
||||
// 构建节点之间的引用(指针)
|
||||
n1.borrow_mut().left = Some(Rc::clone(&n2));
|
||||
n1.borrow_mut().right = Some(Rc::clone(&n3));
|
||||
n2.borrow_mut().left = Some(Rc::clone(&n4));
|
||||
|
||||
Reference in New Issue
Block a user