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

@@ -151,7 +151,7 @@ comments: true
res += i;
}
res
}
}
```
=== "C"
@@ -352,6 +352,7 @@ comments: true
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 @@ comments: true
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

@@ -978,7 +978,7 @@ $$
```rust title="space_complexity.rs"
/* 函数 */
fn function() ->i32 {
fn function() -> i32 {
// 执行某些操作
return 0;
}
@@ -1451,7 +1451,9 @@ $$
/* 线性阶(递归实现) */
fn linear_recur(n: i32) {
println!("递归 n = {}", n);
if n == 1 {return};
if n == 1 {
return;
};
linear_recur(n - 1);
}
```
@@ -1833,7 +1835,9 @@ $$
```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());
@@ -2010,7 +2014,9 @@ $$
```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

@@ -1741,7 +1741,7 @@ $$
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]
@@ -1785,7 +1785,7 @@ $$
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]
@@ -1875,9 +1875,10 @@ $$
/* 平方阶(冒泡排序) */
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]
@@ -1925,7 +1926,7 @@ $$
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]
@@ -2796,10 +2797,10 @@ $$
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;
}
```