This commit is contained in:
krahets
2024-03-18 03:11:07 +08:00
parent bc0054a577
commit 54c7448946
48 changed files with 577 additions and 408 deletions

View File

@ -512,7 +512,7 @@ By comparison, inserting an element into an array has a time complexity of $O(n)
/* 在链表的节点 n0 之后插入节点 P */
#[allow(non_snake_case)]
pub fn insert<T>(n0: &Rc<RefCell<ListNode<T>>>, P: Rc<RefCell<ListNode<T>>>) {
let n1 = n0.borrow_mut().next.take();
let n1 = n0.borrow_mut().next.take();
P.borrow_mut().next = n1;
n0.borrow_mut().next = Some(P);
}
@ -690,7 +690,9 @@ It's important to note that even though node `P` continues to point to `n1` afte
/* 删除链表的节点 n0 之后的首个节点 */
#[allow(non_snake_case)]
pub fn remove<T>(n0: &Rc<RefCell<ListNode<T>>>) {
if n0.borrow().next.is_none() {return};
if n0.borrow().next.is_none() {
return;
};
// n0 -> P -> n1
let P = n0.borrow_mut().next.take();
if let Some(node) = P {
@ -872,10 +874,13 @@ It's important to note that even though node `P` continues to point to `n1` afte
```rust title="linked_list.rs"
/* 访问链表中索引为 index 的节点 */
pub fn access<T>(head: Rc<RefCell<ListNode<T>>>, index: i32) -> Rc<RefCell<ListNode<T>>> {
if index <= 0 {return head};
if let Some(node) = &head.borrow_mut().next {
if index <= 0 {
return head;
};
if let Some(node) = &head.borrow().next {
return access(node.clone(), index - 1);
}
return head;
}
```
@ -1071,7 +1076,9 @@ Traverse the linked list to locate a node whose value matches `target`, and then
```rust title="linked_list.rs"
/* 在链表中查找值为 target 的首个节点 */
pub fn find<T: PartialEq>(head: Rc<RefCell<ListNode<T>>>, target: T, index: i32) -> i32 {
if head.borrow().val == target {return index};
if head.borrow().val == target {
return index;
};
if let Some(node) = &head.borrow_mut().next {
return find(node.clone(), target, index + 1);
}

View File

@ -1785,16 +1785,16 @@ To enhance our understanding of how lists work, we will attempt to implement a s
#[allow(dead_code)]
struct MyList {
arr: Vec<i32>, // 数组(存储列表元素)
capacity: usize, // 列表容量
size: usize, // 列表长度(当前元素数量)
extend_ratio: usize, // 每次列表扩容的倍数
capacity: usize, // 列表容量
size: usize, // 列表长度(当前元素数量)
extend_ratio: usize, // 每次列表扩容的倍数
}
#[allow(unused,unused_comparisons)]
#[allow(unused, unused_comparisons)]
impl MyList {
/* 构造方法 */
pub fn new(capacity: usize) -> Self {
let mut vec = Vec::new();
let mut vec = Vec::new();
vec.resize(capacity, 0);
Self {
arr: vec,
@ -1817,13 +1817,17 @@ To enhance our understanding of how lists work, we will attempt to implement a s
/* 访问元素 */
pub fn get(&self, index: usize) -> i32 {
// 索引如果越界,则抛出异常,下同
if index >= self.size {panic!("索引越界")};
if index >= self.size {
panic!("索引越界")
};
return self.arr[index];
}
/* 更新元素 */
pub fn set(&mut self, index: usize, num: i32) {
if index >= self.size {panic!("索引越界")};
if index >= self.size {
panic!("索引越界")
};
self.arr[index] = num;
}
@ -1840,7 +1844,9 @@ To enhance our understanding of how lists work, we will attempt to implement a s
/* 在中间插入元素 */
pub fn insert(&mut self, index: usize, num: i32) {
if index >= self.size() {panic!("索引越界")};
if index >= self.size() {
panic!("索引越界")
};
// 元素数量超出容量时,触发扩容机制
if self.size == self.capacity() {
self.extend_capacity();
@ -1856,7 +1862,9 @@ To enhance our understanding of how lists work, we will attempt to implement a s
/* 删除元素 */
pub fn remove(&mut self, index: usize) -> i32 {
if index >= self.size() {panic!("索引越界")};
if index >= self.size() {
panic!("索引越界")
};
let num = self.arr[index];
// 将将索引 index 之后的元素都向前移动一位
for j in (index..self.size - 1) {

View File

@ -151,7 +151,7 @@ The following function implements the sum $1 + 2 + \dots + n$ using a `for` loop
res += i;
}
res
}
}
```
=== "C"
@ -352,6 +352,7 @@ Below we use a `while` loop to implement the sum $1 + 2 + \dots + n$:
fn while_loop(n: i32) -> i32 {
let mut res = 0;
let mut i = 1; // 初始化条件变量
// 循环求和 1, 2, ..., n-1, n
while i <= n {
res += i;
@ -570,6 +571,7 @@ For example, in the following code, the condition variable $i$ is updated twice
fn while_loop_ii(n: i32) -> i32 {
let mut res = 0;
let mut i = 1; // 初始化条件变量
// 循环求和 1, 4, 10, ...
while i <= n {
res += i;

View File

@ -979,7 +979,7 @@ Note that memory occupied by initializing variables or calling functions in a lo
```rust title="space_complexity.rs"
/* 函数 */
fn function() ->i32 {
fn function() -> i32 {
// 执行某些操作
return 0;
}
@ -1452,7 +1452,9 @@ As shown below, this function's recursive depth is $n$, meaning there are $n$ in
/* 线性阶(递归实现) */
fn linear_recur(n: i32) {
println!("递归 n = {}", n);
if n == 1 {return};
if n == 1 {
return;
};
linear_recur(n - 1);
}
```
@ -1834,7 +1836,9 @@ As shown below, the recursive depth of this function is $n$, and in each recursi
```rust title="space_complexity.rs"
/* 平方阶(递归实现) */
fn quadratic_recur(n: i32) -> i32 {
if n <= 0 {return 0};
if n <= 0 {
return 0;
};
// 数组 nums 长度为 n, n-1, ..., 2, 1
let nums = vec![0; n as usize];
println!("递归 n = {} 中的 nums 长度 = {}", n, nums.len());
@ -2011,7 +2015,9 @@ Exponential order is common in binary trees. Observe the below image, a "full bi
```rust title="space_complexity.rs"
/* 指数阶(建立满二叉树) */
fn build_tree(n: i32) -> Option<Rc<RefCell<TreeNode>>> {
if n == 0 {return None};
if n == 0 {
return None;
};
let root = TreeNode::new(0);
root.borrow_mut().left = build_tree(n - 1);
root.borrow_mut().right = build_tree(n - 1);

View File

@ -1737,7 +1737,7 @@ For instance, in bubble sort, the outer loop runs $n - 1$ times, and the inner l
int count = 0; // 计数器
// 外循环:未排序区间为 [0, i]
for (int i = nums.Length - 1; i > 0; i--) {
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// 交换 nums[j] 与 nums[j + 1]
@ -1781,7 +1781,7 @@ For instance, in bubble sort, the outer loop runs $n - 1$ times, and the inner l
var count = 0 // 计数器
// 外循环:未排序区间为 [0, i]
for i in stride(from: nums.count - 1, to: 0, by: -1) {
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
for j in 0 ..< i {
if nums[j] > nums[j + 1] {
// 交换 nums[j] 与 nums[j + 1]
@ -1871,9 +1871,10 @@ For instance, in bubble sort, the outer loop runs $n - 1$ times, and the inner l
/* 平方阶(冒泡排序) */
fn bubble_sort(nums: &mut [i32]) -> i32 {
let mut count = 0; // 计数器
// 外循环:未排序区间为 [0, i]
for i in (1..nums.len()).rev() {
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
for j in 0..i {
if nums[j] > nums[j + 1] {
// 交换 nums[j] 与 nums[j + 1]
@ -1921,7 +1922,7 @@ For instance, in bubble sort, the outer loop runs $n - 1$ times, and the inner l
var i: i32 = @as(i32, @intCast(nums.len)) - 1;
while (i > 0) : (i -= 1) {
var j: usize = 0;
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
while (j < i) : (j += 1) {
if (nums[j] > nums[j + 1]) {
// 交换 nums[j] 与 nums[j + 1]
@ -2792,10 +2793,10 @@ Linear-logarithmic order often appears in nested loops, with the complexities of
return 1;
}
let mut count = linear_log_recur(n / 2.0) + linear_log_recur(n / 2.0);
for _ in 0 ..n as i32 {
for _ in 0..n as i32 {
count += 1;
}
return count
return count;
}
```

View File

@ -469,7 +469,7 @@ The design of hash algorithms is a complex issue that requires consideration of
}
hash as i32
}
}
/* 乘法哈希 */
fn mul_hash(key: &str) -> i32 {

View File

@ -1863,129 +1863,113 @@ The code below implements an open addressing (linear probing) hash table with la
capacity int // 哈希表容量
loadThres float64 // 触发扩容的负载因子阈值
extendRatio int // 扩容倍数
buckets []pair // 桶数组
removed pair // 删除标记
buckets []*pair // 桶数组
TOMBSTONE *pair // 删除标记
}
/* 构造方法 */
func newHashMapOpenAddressing() *hashMapOpenAddressing {
buckets := make([]pair, 4)
return &hashMapOpenAddressing{
size: 0,
capacity: 4,
loadThres: 2.0 / 3.0,
extendRatio: 2,
buckets: buckets,
removed: pair{
key: -1,
val: "-1",
},
buckets: make([]*pair, 4),
TOMBSTONE: &pair{-1, "-1"},
}
}
/* 哈希函数 */
func (m *hashMapOpenAddressing) hashFunc(key int) int {
return key % m.capacity
func (h *hashMapOpenAddressing) hashFunc(key int) int {
return key % h.capacity // 根据键计算哈希值
}
/* 负载因子 */
func (m *hashMapOpenAddressing) loadFactor() float64 {
return float64(m.size) / float64(m.capacity)
func (h *hashMapOpenAddressing) loadFactor() float64 {
return float64(h.size) / float64(h.capacity) // 计算当前负载因子
}
/* 搜索 key 对应的桶索引 */
func (h *hashMapOpenAddressing) findBucket(key int) int {
index := h.hashFunc(key) // 获取初始索引
firstTombstone := -1 // 记录遇到的第一个TOMBSTONE的位置
for h.buckets[index] != nil {
if h.buckets[index].key == key {
if firstTombstone != -1 {
// 若之前遇到了删除标记,则将键值对移动至该索引处
h.buckets[firstTombstone] = h.buckets[index]
h.buckets[index] = h.TOMBSTONE
return firstTombstone // 返回移动后的桶索引
}
return index // 返回找到的索引
}
if firstTombstone == -1 && h.buckets[index] == h.TOMBSTONE {
firstTombstone = index // 记录遇到的首个删除标记的位置
}
index = (index + 1) % h.capacity // 线性探测,越过尾部则返回头部
}
// 若 key 不存在,则返回添加点的索引
if firstTombstone != -1 {
return firstTombstone
}
return index
}
/* 查询操作 */
func (m *hashMapOpenAddressing) get(key int) string {
idx := m.hashFunc(key)
// 线性探测,从 index 开始向后遍历
for i := 0; i < m.capacity; i++ {
// 计算桶索引,越过尾部则返回头部
j := (idx + i) % m.capacity
// 若遇到空桶,说明无此 key ,则返回 null
if m.buckets[j] == (pair{}) {
return ""
}
// 若遇到指定 key ,则返回对应 val
if m.buckets[j].key == key && m.buckets[j] != m.removed {
return m.buckets[j].val
}
func (h *hashMapOpenAddressing) get(key int) string {
index := h.findBucket(key) // 搜索 key 对应的桶索引
if h.buckets[index] != nil && h.buckets[index] != h.TOMBSTONE {
return h.buckets[index].val // 若找到键值对,则返回对应 val
}
// 若未找到 key ,则返回空字符串
return ""
return "" // 若键值对不存在,则返回 ""
}
/* 添加操作 */
func (m *hashMapOpenAddressing) put(key int, val string) {
// 当负载因子超过阈值时,执行扩容
if m.loadFactor() > m.loadThres {
m.extend()
func (h *hashMapOpenAddressing) put(key int, val string) {
if h.loadFactor() > h.loadThres {
h.extend() // 当负载因子超过阈值时,执行扩容
}
idx := m.hashFunc(key)
// 线性探测,从 index 开始向后遍历
for i := 0; i < m.capacity; i++ {
// 计算桶索引,越过尾部则返回头部
j := (idx + i) % m.capacity
// 若遇到空桶、或带有删除标记的桶,则将键值对放入该桶
if m.buckets[j] == (pair{}) || m.buckets[j] == m.removed {
m.buckets[j] = pair{
key: key,
val: val,
}
m.size += 1
return
}
// 若遇到指定 key ,则更新对应 val
if m.buckets[j].key == key {
m.buckets[j].val = val
return
}
index := h.findBucket(key) // 搜索 key 对应的桶索引
if h.buckets[index] == nil || h.buckets[index] == h.TOMBSTONE {
h.buckets[index] = &pair{key, val} // 若键值对不存在,则添加该键值对
h.size++
} else {
h.buckets[index].val = val // 若找到键值对,则覆盖 val
}
}
/* 删除操作 */
func (m *hashMapOpenAddressing) remove(key int) {
idx := m.hashFunc(key)
// 遍历桶,从中删除键值对
// 线性探测,从 index 开始向后遍历
for i := 0; i < m.capacity; i++ {
// 计算桶索引,越过尾部则返回头部
j := (idx + i) % m.capacity
// 若遇到空桶,说明无此 key ,则直接返回
if m.buckets[j] == (pair{}) {
return
}
// 若遇到指定 key ,则标记删除并返回
if m.buckets[j].key == key {
m.buckets[j] = m.removed
m.size -= 1
}
func (h *hashMapOpenAddressing) remove(key int) {
index := h.findBucket(key) // 搜索 key 对应的桶索引
if h.buckets[index] != nil && h.buckets[index] != h.TOMBSTONE {
h.buckets[index] = h.TOMBSTONE // 若找到键值对,则用删除标记覆盖它
h.size--
}
}
/* 扩容哈希表 */
func (m *hashMapOpenAddressing) extend() {
// 暂存原哈希表
tmpBuckets := make([]pair, len(m.buckets))
copy(tmpBuckets, m.buckets)
// 初始化扩容后的新哈希表
m.capacity *= m.extendRatio
m.buckets = make([]pair, m.capacity)
m.size = 0
func (h *hashMapOpenAddressing) extend() {
oldBuckets := h.buckets // 暂存原哈希表
h.capacity *= h.extendRatio // 更新容量
h.buckets = make([]*pair, h.capacity) // 初始化扩容后的新哈希表
h.size = 0 // 重置大小
// 将键值对从原哈希表搬运至新哈希表
for _, p := range tmpBuckets {
if p != (pair{}) && p != m.removed {
m.put(p.key, p.val)
for _, pair := range oldBuckets {
if pair != nil && pair != h.TOMBSTONE {
h.put(pair.key, pair.val)
}
}
}
/* 打印哈希表 */
func (m *hashMapOpenAddressing) print() {
for _, p := range m.buckets {
if p != (pair{}) {
fmt.Println(strconv.Itoa(p.key) + " -> " + p.val)
} else {
func (h *hashMapOpenAddressing) print() {
for _, pair := range h.buckets {
if pair == nil {
fmt.Println("nil")
} else if pair == h.TOMBSTONE {
fmt.Println("TOMBSTONE")
} else {
fmt.Printf("%d -> %s\n", pair.key, pair.val)
}
}
}
@ -2540,15 +2524,14 @@ The code below implements an open addressing (linear probing) hash table with la
```rust title="hash_map_open_addressing.rs"
/* 开放寻址哈希表 */
struct HashMapOpenAddressing {
size: usize, // 键值对数量
capacity: usize, // 哈希表容量
load_thres: f64, // 触发扩容的负载因子阈值
extend_ratio: usize, // 扩容倍数
buckets: Vec<Option<Pair>>, // 桶数组
TOMBSTONE: Option<Pair>, // 删除标记
size: usize, // 键值对数量
capacity: usize, // 哈希表容量
load_thres: f64, // 触发扩容的负载因子阈值
extend_ratio: usize, // 扩容倍数
buckets: Vec<Option<Pair>>, // 桶数组
TOMBSTONE: Option<Pair>, // 删除标记
}
impl HashMapOpenAddressing {
/* 构造方法 */
fn new() -> Self {
@ -2558,7 +2541,10 @@ The code below implements an open addressing (linear probing) hash table with la
load_thres: 2.0 / 3.0,
extend_ratio: 2,
buckets: vec![None; 4],
TOMBSTONE: Some(Pair {key: -1, val: "-1".to_string()}),
TOMBSTONE: Some(Pair {
key: -1,
val: "-1".to_string(),
}),
}
}
@ -2584,9 +2570,9 @@ The code below implements an open addressing (linear probing) hash table with la
if first_tombstone != -1 {
self.buckets[first_tombstone as usize] = self.buckets[index].take();
self.buckets[index] = self.TOMBSTONE.clone();
return first_tombstone as usize; // 返回移动后的桶索引
return first_tombstone as usize; // 返回移动后的桶索引
}
return index; // 返回桶索引
return index; // 返回桶索引
}
// 记录遇到的首个删除标记
if first_tombstone == -1 && self.buckets[index] == self.TOMBSTONE {
@ -2596,7 +2582,11 @@ The code below implements an open addressing (linear probing) hash table with la
index = (index + 1) % self.capacity;
}
// 若 key 不存在,则返回添加点的索引
if first_tombstone == -1 { index } else { first_tombstone as usize }
if first_tombstone == -1 {
index
} else {
first_tombstone as usize
}
}
/* 查询操作 */

View File

@ -1343,13 +1343,15 @@ The following code implements a simple hash table. Here, we encapsulate `key` an
/* 基于数组实现的哈希表 */
pub struct ArrayHashMap {
buckets: Vec<Option<Pair>>
buckets: Vec<Option<Pair>>,
}
impl ArrayHashMap {
pub fn new() -> ArrayHashMap {
// 初始化数组,包含 100 个桶
Self { buckets: vec![None; 100] }
Self {
buckets: vec![None; 100],
}
}
/* 哈希函数 */
@ -1381,17 +1383,26 @@ The following code implements a simple hash table. Here, we encapsulate `key` an
/* 获取所有键值对 */
pub fn entry_set(&self) -> Vec<&Pair> {
self.buckets.iter().filter_map(|pair| pair.as_ref()).collect()
self.buckets
.iter()
.filter_map(|pair| pair.as_ref())
.collect()
}
/* 获取所有键 */
pub fn key_set(&self) -> Vec<&i32> {
self.buckets.iter().filter_map(|pair| pair.as_ref().map(|pair| &pair.key)).collect()
self.buckets
.iter()
.filter_map(|pair| pair.as_ref().map(|pair| &pair.key))
.collect()
}
/* 获取所有值 */
pub fn value_set(&self) -> Vec<&String> {
self.buckets.iter().filter_map(|pair| pair.as_ref().map(|pair| &pair.val)).collect()
self.buckets
.iter()
.filter_map(|pair| pair.as_ref().map(|pair| &pair.val))
.collect()
}
/* 打印哈希表 */

View File

@ -1522,9 +1522,9 @@ The implementation code is as follows:
/* 基于双向链表实现的双向队列 */
#[allow(dead_code)]
pub struct LinkedListDeque<T> {
front: Option<Rc<RefCell<ListNode<T>>>>, // 头节点 front
rear: Option<Rc<RefCell<ListNode<T>>>>, // 尾节点 rear
que_size: usize, // 双向队列的长度
front: Option<Rc<RefCell<ListNode<T>>>>, // 头节点 front
rear: Option<Rc<RefCell<ListNode<T>>>>, // 尾节点 rear
que_size: usize, // 双向队列的长度
}
impl<T: Copy> LinkedListDeque<T> {
@ -1532,7 +1532,7 @@ The implementation code is as follows:
Self {
front: None,
rear: None,
que_size: 0,
que_size: 0,
}
}
@ -1564,7 +1564,7 @@ The implementation code is as follows:
self.front = Some(node); // 更新头节点
}
}
}
}
// 队尾入队操作
else {
match self.rear.take() {
@ -1597,8 +1597,8 @@ The implementation code is as follows:
/* 出队操作 */
pub fn pop(&mut self, is_front: bool) -> Option<T> {
// 若队列为空,直接返回 None
if self.is_empty() {
return None
if self.is_empty() {
return None;
};
// 队首出队操作
if is_front {
@ -1606,7 +1606,7 @@ The implementation code is as follows:
match old_front.borrow_mut().next.take() {
Some(new_front) => {
new_front.borrow_mut().prev.take();
self.front = Some(new_front); // 更新头节点
self.front = Some(new_front); // 更新头节点
}
None => {
self.rear.take();
@ -1615,15 +1615,14 @@ The implementation code is as follows:
self.que_size -= 1; // 更新队列长度
Rc::try_unwrap(old_front).ok().unwrap().into_inner().val
})
}
}
// 队尾出队操作
else {
self.rear.take().map(|old_rear| {
match old_rear.borrow_mut().prev.take() {
Some(new_rear) => {
new_rear.borrow_mut().next.take();
self.rear = Some(new_rear); // 更新尾节点
self.rear = Some(new_rear); // 更新尾节点
}
None => {
self.front.take();

View File

@ -959,9 +959,9 @@ Below is the code for implementing a queue using a linked list:
/* 基于链表实现的队列 */
#[allow(dead_code)]
pub struct LinkedListQueue<T> {
front: Option<Rc<RefCell<ListNode<T>>>>, // 头节点 front
rear: Option<Rc<RefCell<ListNode<T>>>>, // 尾节点 rear
que_size: usize, // 队列的长度
front: Option<Rc<RefCell<ListNode<T>>>>, // 头节点 front
rear: Option<Rc<RefCell<ListNode<T>>>>, // 尾节点 rear
que_size: usize, // 队列的长度
}
impl<T: Copy> LinkedListQueue<T> {
@ -969,7 +969,7 @@ Below is the code for implementing a queue using a linked list:
Self {
front: None,
rear: None,
que_size: 0,
que_size: 0,
}
}
@ -1887,10 +1887,10 @@ For a circular array, `front` or `rear` needs to loop back to the start of the a
```rust title="array_queue.rs"
/* 基于环形数组实现的队列 */
struct ArrayQueue {
nums: Vec<i32>, // 用于存储队列元素的数组
front: i32, // 队首指针,指向队首元素
que_size: i32, // 队列长度
que_capacity: i32, // 队列容量
nums: Vec<i32>, // 用于存储队列元素的数组
front: i32, // 队首指针,指向队首元素
que_size: i32, // 队列长度
que_capacity: i32, // 队列容量
}
impl ArrayQueue {

View File

@ -876,8 +876,8 @@ Below is an example code for implementing a stack based on a linked list:
/* 基于链表实现的栈 */
#[allow(dead_code)]
pub struct LinkedListStack<T> {
stack_peek: Option<Rc<RefCell<ListNode<T>>>>, // 将头节点作为栈顶
stk_size: usize, // 栈的长度
stack_peek: Option<Rc<RefCell<ListNode<T>>>>, // 将头节点作为栈顶
stk_size: usize, // 栈的长度
}
impl<T: Copy> LinkedListStack<T> {
@ -1537,7 +1537,9 @@ Since the elements to be pushed onto the stack may continuously increase, we can
impl<T> ArrayStack<T> {
/* 初始化栈 */
fn new() -> ArrayStack<T> {
ArrayStack::<T> { stack: Vec::<T>::new() }
ArrayStack::<T> {
stack: Vec::<T>::new(),
}
}
/* 获取栈的长度 */
@ -1565,7 +1567,9 @@ Since the elements to be pushed onto the stack may continuously increase, we can
/* 访问栈顶元素 */
fn peek(&self) -> Option<&T> {
if self.is_empty() { panic!("栈为空") };
if self.is_empty() {
panic!("栈为空")
};
self.stack.last()
}