Complement to Rust code in the Chapter array and linked list / Time Complexity. (#657)

* Complement to Rust code in the Chapter array and linked list

* Complement to Rust code in the Time Complexity

* Remove this Rust struct from 380 to 383.

* Address the comments from @night-cruise

* Add more comments in list and time complexity

* Add more comments in linked list
This commit is contained in:
埃拉
2023-08-07 18:22:04 +08:00
committed by GitHub
parent 4bc6b8af7b
commit 9ed16db68e
4 changed files with 131 additions and 8 deletions

View File

@@ -119,7 +119,11 @@
=== "Rust"
```rust title="list.rs"
/* 初始化列表 */
// 无初始值
let list1: Vec<i32> = Vec::new();
// 有初始值
let list2: Vec<i32> = vec![1, 3, 2, 5, 4];
```
**访问与更新元素**。由于列表的底层数据结构是数组,因此可以在 $O(1)$ 时间内访问和更新元素,效率很高。
@@ -233,7 +237,10 @@
=== "Rust"
```rust title="list.rs"
/* 访问元素 */
let num: i32 = list[1]; // 访问索引 1 处的元素
/* 更新元素 */
list[1] = 0; // 将索引 1 处的元素更新为 0
```
**在列表中添加、插入、删除元素**。相较于数组,列表可以自由地添加与删除元素。在列表尾部添加元素的时间复杂度为 $O(1)$ ,但插入和删除元素的效率仍与数组相同,时间复杂度为 $O(N)$ 。
@@ -447,7 +454,21 @@
=== "Rust"
```rust title="list.rs"
/* 清空列表 */
list.clear();
/* 尾部添加元素 */
list.push(1);
list.push(3);
list.push(2);
list.push(5);
list.push(4);
/* 中间插入元素 */
list.insert(3, 6); // 在索引 3 处插入数字 6
/* 删除元素 */
list.remove(3); // 删除索引 3 处的元素
```
**遍历列表**。与数组一样,列表可以根据索引遍历,也可以直接遍历各元素。
@@ -620,7 +641,17 @@
=== "Rust"
```rust title="list.rs"
/* 通过索引遍历列表 */
let mut count = 0;
for (index, value) in list.iter().enumerate() {
count += 1;
}
/* 直接遍历列表元素 */
let mut count = 0;
for value in list.iter() {
count += 1;
}
```
**拼接两个列表**。给定一个新列表 `list1` ,我们可以将该列表拼接到原列表的尾部。
@@ -717,7 +748,9 @@
=== "Rust"
```rust title="list.rs"
/* 拼接两个列表 */
let list1: Vec<i32> = vec![6, 8, 7, 10, 9];
list.extend(list1);
```
**排序列表**。排序也是常用的方法之一。完成列表排序后,我们便可以使用在数组类算法题中经常考察的「二分查找」和「双指针」算法。
@@ -801,7 +834,8 @@
=== "Rust"
```rust title="list.rs"
/* 排序列表 */
list.sort(); // 排序后,列表元素从小到大排列
```
## 列表实现 *