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

@ -171,7 +171,16 @@ $$
=== "Rust"
```rust title=""
// 在某运行平台下
fn algorithm(n: i32) {
let mut a = 2; // 1 ns
a = a + 1; // 1 ns
a = a * 2; // 10 ns
// 循环 n 次
for _ in 0..n { // 1 ns ,每轮都要执行 i++
println!("{}", 0); // 5 ns
}
}
```
然而实际上,**统计算法的运行时间既不合理也不现实**。首先,我们不希望预估时间和运行平台绑定,因为算法需要在各种不同的平台上运行。其次,我们很难获知每种操作的运行时间,这给预估过程带来了极大的难度。
@ -403,7 +412,22 @@ $$
=== "Rust"
```rust title=""
// 算法 A 时间复杂度:常数阶
fn algorithm_A(n: i32) {
println!("{}", 0);
}
// 算法 B 时间复杂度:线性阶
fn algorithm_B(n: i32) {
for _ in 0..n {
println!("{}", 0);
}
}
// 算法 C 时间复杂度:常数阶
fn algorithm_C(n: i32) {
for _ in 0..1000000 {
println!("{}", 0);
}
}
```
![算法 A, B, C 的时间增长趋势](time_complexity.assets/time_complexity_simple_example.png)
@ -571,7 +595,16 @@ $$
=== "Rust"
```rust title=""
fn algorithm(n: i32) {
let mut a = 1; // +1
a = a + 1; // +1
a = a * 2; // +1
// 循环 n 次
for _ in 0..n { // +1每轮都执行 i ++
println!("{}", 0); // +1
}
}
```
$T(n)$ 是一次函数,说明时间增长趋势是线性的,因此可以得出时间复杂度是线性阶。
@ -816,7 +849,22 @@ $$
=== "Rust"
```rust title=""
fn algorithm(n: i32) {
let mut a = 1; // +0技巧 1
a = a + n; // +0技巧 1
// +n技巧 2
for i in 0..(5 * n + 1) {
println!("{}", 0);
}
// +n*n技巧 3
for i in 0..(2 * n) {
for j in 0..(n + 1) {
println!("{}", 0);
}
}
}
```
### 第二步:判断渐近上界