cargo fmt rust code (#1131)

* cargo fmt code

* Add empty line to seperate unrelated comments

* Fix review

* Update bubble_sort.rs

* Update merge_sort.rs

---------

Co-authored-by: Yudong Jin <krahets@163.com>
This commit is contained in:
rongyi
2024-03-16 02:13:41 +08:00
committed by GitHub
parent 54ceef3443
commit 7b1094318b
70 changed files with 1021 additions and 836 deletions

View File

@ -6,9 +6,9 @@
include!("../include/include.rs");
use std::rc::Rc;
use std::cell::RefCell;
use list_node::ListNode;
use std::cell::RefCell;
use std::rc::Rc;
/* 在链表的节点 n0 之后插入节点 P */
#[allow(non_snake_case)]
@ -21,7 +21,9 @@ pub fn insert<T>(n0: &Rc<RefCell<ListNode<T>>>, P: Rc<RefCell<ListNode<T>>>) {
/* 删除链表的节点 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 {
@ -32,7 +34,9 @@ pub fn remove<T>(n0: &Rc<RefCell<ListNode<T>>>) {
/* 访问链表中索引为 index 的节点 */
pub fn access<T>(head: Rc<RefCell<ListNode<T>>>, index: i32) -> Rc<RefCell<ListNode<T>>> {
if index <= 0 {return head};
if index <= 0 {
return head;
};
if let Some(node) = &head.borrow_mut().next {
return access(node.clone(), index - 1);
}
@ -41,7 +45,9 @@ pub fn access<T>(head: Rc<RefCell<ListNode<T>>>, index: i32) -> Rc<RefCell<ListN
/* 在链表中查找值为 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

@ -60,6 +60,7 @@ fn main() {
// 拼接两个列表
let mut nums1 = vec![6, 8, 7, 10, 9];
nums.append(&mut nums1); // append移动 之后 nums1 为空!
// nums.extend(&nums1); // extend借用 nums1 能继续使用
print!("\n将列表 nums1 拼接到 nums 之后,得到 nums = ");
print_util::print_array(&nums);

View File

@ -42,13 +42,17 @@ impl MyList {
/* 访问元素 */
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;
}
@ -65,7 +69,9 @@ impl MyList {
/* 在中间插入元素 */
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();
@ -81,7 +87,9 @@ impl MyList {
/* 删除元素 */
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

@ -5,8 +5,15 @@
*/
/* 回溯算法n 皇后 */
fn backtrack(row: usize, n: usize, state: &mut Vec<Vec<String>>, res: &mut Vec<Vec<Vec<String>>>,
cols: &mut [bool], diags1: &mut [bool], diags2: &mut [bool]) {
fn backtrack(
row: usize,
n: usize,
state: &mut Vec<Vec<String>>,
res: &mut Vec<Vec<Vec<String>>>,
cols: &mut [bool],
diags1: &mut [bool],
diags2: &mut [bool],
) {
// 当放置完所有行时,记录解
if row == n {
let mut copy_state: Vec<Vec<String>> = Vec::new();
@ -51,7 +58,15 @@ fn n_queens(n: usize) -> Vec<Vec<Vec<String>>> {
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);
backtrack(
0,
n,
&mut state,
&mut res,
&mut cols,
&mut diags1,
&mut diags2,
);
res
}

View File

@ -10,7 +10,11 @@ use std::{cell::RefCell, rc::Rc};
use tree_node::{vec_to_tree, TreeNode};
/* 前序遍历:例题二 */
fn pre_order(res: &mut Vec<Vec<Rc<RefCell<TreeNode>>>>, path: &mut Vec<Rc<RefCell<TreeNode>>>, root: Option<Rc<RefCell<TreeNode>>>) {
fn pre_order(
res: &mut Vec<Vec<Rc<RefCell<TreeNode>>>>,
path: &mut Vec<Rc<RefCell<TreeNode>>>,
root: Option<Rc<RefCell<TreeNode>>>,
) {
if root.is_none() {
return;
}

View File

@ -10,7 +10,11 @@ use std::{cell::RefCell, rc::Rc};
use tree_node::{vec_to_tree, TreeNode};
/* 前序遍历:例题三 */
fn pre_order(res: &mut Vec<Vec<Rc<RefCell<TreeNode>>>>, path: &mut Vec<Rc<RefCell<TreeNode>>>, root: Option<Rc<RefCell<TreeNode>>>) {
fn pre_order(
res: &mut Vec<Vec<Rc<RefCell<TreeNode>>>>,
path: &mut Vec<Rc<RefCell<TreeNode>>>,
root: Option<Rc<RefCell<TreeNode>>>,
) {
// 剪枝
if root.is_none() || root.as_ref().unwrap().borrow().val == 3 {
return;

View File

@ -15,7 +15,10 @@ fn is_solution(state: &mut Vec<Rc<RefCell<TreeNode>>>) -> bool {
}
/* 记录解 */
fn record_solution(state: &mut Vec<Rc<RefCell<TreeNode>>>, res: &mut Vec<Vec<Rc<RefCell<TreeNode>>>>) {
fn record_solution(
state: &mut Vec<Rc<RefCell<TreeNode>>>,
res: &mut Vec<Vec<Rc<RefCell<TreeNode>>>>,
) {
res.push(state.clone());
}
@ -35,7 +38,11 @@ fn undo_choice(state: &mut Vec<Rc<RefCell<TreeNode>>>, _: Rc<RefCell<TreeNode>>)
}
/* 回溯算法:例题三 */
fn backtrack(state: &mut Vec<Rc<RefCell<TreeNode>>>, choices: &mut Vec<Rc<RefCell<TreeNode>>>, res: &mut Vec<Vec<Rc<RefCell<TreeNode>>>>) {
fn backtrack(
state: &mut Vec<Rc<RefCell<TreeNode>>>,
choices: &mut Vec<Rc<RefCell<TreeNode>>>,
res: &mut Vec<Vec<Rc<RefCell<TreeNode>>>>,
) {
// 检查是否为解
if is_solution(state) {
// 记录解
@ -48,7 +55,14 @@ fn backtrack(state: &mut Vec<Rc<RefCell<TreeNode>>>, choices: &mut Vec<Rc<RefCel
// 尝试:做出选择,更新状态
make_choice(state, choice.clone());
// 进行下一轮选择
backtrack(state, &mut vec![choice.borrow().left.clone().unwrap(), choice.borrow().right.clone().unwrap()], res);
backtrack(
state,
&mut vec![
choice.borrow().left.clone().unwrap(),
choice.borrow().right.clone().unwrap(),
],
res,
);
// 回退:撤销选择,恢复到之前的状态
undo_choice(state, choice.clone());
}

View File

@ -5,7 +5,13 @@
*/
/* 回溯算法:子集和 I */
fn backtrack(mut state: Vec<i32>, target: i32, choices: &[i32], start: usize, res: &mut Vec<Vec<i32>>) {
fn backtrack(
mut state: Vec<i32>,
target: i32,
choices: &[i32],
start: usize,
res: &mut Vec<Vec<i32>>,
) {
// 子集和等于 target 时,记录解
if target == 0 {
res.push(state);

View File

@ -5,7 +5,13 @@
*/
/* 回溯算法:子集和 I */
fn backtrack(mut state: Vec<i32>, target: i32, total: i32, choices: &[i32], res: &mut Vec<Vec<i32>>) {
fn backtrack(
mut state: Vec<i32>,
target: i32,
total: i32,
choices: &[i32],
res: &mut Vec<Vec<i32>>,
) {
// 子集和等于 target 时,记录解
if total == target {
res.push(state);

View File

@ -5,7 +5,13 @@
*/
/* 回溯算法:子集和 II */
fn backtrack(mut state: Vec<i32>, target: i32, choices: &[i32], start: usize, res: &mut Vec<Vec<i32>>) {
fn backtrack(
mut state: Vec<i32>,
target: i32,
choices: &[i32],
start: usize,
res: &mut Vec<Vec<i32>>,
) {
// 子集和等于 target 时,记录解
if target == 0 {
res.push(state);

View File

@ -4,7 +4,6 @@
* Author: night-cruise (2586447362@qq.com)
*/
/* for 循环 */
fn for_loop(n: i32) -> i32 {
let mut res = 0;
@ -19,6 +18,7 @@ fn for_loop(n: i32) -> i32 {
fn while_loop(n: i32) -> i32 {
let mut res = 0;
let mut i = 1; // 初始化条件变量
// 循环求和 1, 2, ..., n-1, n
while i <= n {
res += i;
@ -31,6 +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, 10, ...
while i <= n {
res += i;

View File

@ -4,7 +4,6 @@
* Author: night-cruise (2586447362@qq.com)
*/
/* 递归 */
fn recur(n: i32) -> i32 {
// 终止条件

View File

@ -6,10 +6,10 @@
include!("../include/include.rs");
use list_node::ListNode;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::cell::RefCell;
use list_node::ListNode;
use tree_node::TreeNode;
/* 函数 */
@ -56,7 +56,9 @@ fn linear(n: i32) {
/* 线性阶(递归实现) */
fn linear_recur(n: i32) {
println!("递归 n = {}", n);
if n == 1 {return};
if n == 1 {
return;
};
linear_recur(n - 1);
}
@ -78,7 +80,9 @@ fn quadratic(n: i32) {
/* 平方阶(递归实现) */
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());
@ -87,7 +91,9 @@ fn quadratic_recur(n: i32) -> i32 {
/* 指数阶(建立满二叉树) */
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

@ -49,6 +49,7 @@ fn quadratic(n: i32) -> i32 {
/* 平方阶(冒泡排序) */
fn bubble_sort(nums: &mut [i32]) -> i32 {
let mut count = 0; // 计数器
// 外循环:未排序区间为 [0, i]
for i in (1..nums.len()).rev() {
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
@ -115,7 +116,7 @@ fn linear_log_recur(n: f32) -> i32 {
for _ in 0..n as i32 {
count += 1;
}
return count
return count;
}
/* 阶乘阶(递归实现) */

View File

@ -7,7 +7,9 @@
/* 二分查找:问题 f(i, j) */
fn dfs(nums: &[i32], target: i32, i: i32, j: i32) -> i32 {
// 若区间为空,代表无目标元素,则返回 -1
if i > j { return -1; }
if i > j {
return -1;
}
let m: i32 = (i + j) / 2;
if nums[m as usize] < target {
// 递归子问题 f(m+1, j)

View File

@ -4,15 +4,23 @@
* Author: codingonion (coderonion@gmail.com)
*/
use std::{cell::RefCell, rc::Rc};
use std::collections::HashMap;
use std::{cell::RefCell, rc::Rc};
include!("../include/include.rs");
use tree_node::TreeNode;
/* 构建二叉树:分治 */
fn dfs(preorder: &[i32], inorder_map: &HashMap<i32, i32>, i: i32, l: i32, r: i32) -> Option<Rc<RefCell<TreeNode>>> {
fn dfs(
preorder: &[i32],
inorder_map: &HashMap<i32, i32>,
i: i32,
l: i32,
r: i32,
) -> Option<Rc<RefCell<TreeNode>>> {
// 子树区间为空时终止
if r - l < 0 { return None; }
if r - l < 0 {
return None;
}
// 初始化根节点
let root = TreeNode::new(preorder[i as usize]);
// 查询 m ,从而划分左右子树

View File

@ -7,11 +7,15 @@
/* 回溯 */
fn backtrack(choices: &[i32], state: i32, n: i32, res: &mut [i32]) {
// 当爬到第 n 阶时,方案数量加 1
if state == n { res[0] = res[0] + 1; }
if state == n {
res[0] = res[0] + 1;
}
// 遍历所有选择
for &choice in choices {
// 剪枝:不允许越过第 n 阶
if state + choice > n { continue; }
if state + choice > n {
continue;
}
// 尝试:做出选择,更新状态
backtrack(choices, state + choice, n, res);
// 回退

View File

@ -6,7 +6,9 @@
/* 带约束爬楼梯:动态规划 */
fn climbing_stairs_constraint_dp(n: usize) -> i32 {
if n == 1 || n == 2 { return 1 };
if n == 1 || n == 2 {
return 1;
};
// 初始化 dp 表,用于存储子问题的解
let mut dp = vec![vec![-1; 3]; n + 1];
// 初始状态:预设最小子问题的解

View File

@ -7,7 +7,9 @@
/* 搜索 */
fn dfs(i: usize) -> i32 {
// 已知 dp[1] 和 dp[2] ,返回之
if i == 1 || i == 2 { return i as i32; }
if i == 1 || i == 2 {
return i as i32;
}
// dp[i] = dp[i-1] + dp[i-2]
let count = dfs(i - 1) + dfs(i - 2);
count

View File

@ -7,9 +7,13 @@
/* 记忆化搜索 */
fn dfs(i: usize, mem: &mut [i32]) -> i32 {
// 已知 dp[1] 和 dp[2] ,返回之
if i == 1 || i == 2 { return i as i32; }
if i == 1 || i == 2 {
return i as i32;
}
// 若存在记录 dp[i] ,则直接返回之
if mem[i] != -1 { return mem[i]; }
if mem[i] != -1 {
return mem[i];
}
// dp[i] = dp[i-1] + dp[i-2]
let count = dfs(i - 1, mem) + dfs(i - 2, mem);
// 记录 dp[i]

View File

@ -7,7 +7,9 @@
/* 爬楼梯:动态规划 */
fn climbing_stairs_dp(n: usize) -> i32 {
// 已知 dp[1] 和 dp[2] ,返回之
if n == 1 || n == 2 { return n as i32; }
if n == 1 || n == 2 {
return n as i32;
}
// 初始化 dp 表,用于存储子问题的解
let mut dp = vec![-1; n + 1];
// 初始状态:预设最小子问题的解
@ -22,7 +24,9 @@ fn climbing_stairs_dp(n: usize) -> i32 {
/* 爬楼梯:空间优化后的动态规划 */
fn climbing_stairs_dp_comp(n: usize) -> i32 {
if n == 1 || n == 2 { return n as i32; }
if n == 1 || n == 2 {
return n as i32;
}
let (mut a, mut b) = (1, 2);
for _ in 3..=n {
let tmp = b;

View File

@ -26,7 +26,11 @@ fn coin_change_dp(coins: &[i32], amt: usize) -> i32 {
}
}
}
if dp[n][amt] != max { return dp[n][amt] as i32; } else { -1 }
if dp[n][amt] != max {
return dp[n][amt] as i32;
} else {
-1
}
}
/* 零钱兑换:空间优化后的动态规划 */
@ -49,7 +53,11 @@ fn coin_change_dp_comp(coins: &[i32], amt: usize) -> i32 {
}
}
}
if dp[amt] != max { return dp[amt] as i32; } else { -1 }
if dp[amt] != max {
return dp[amt] as i32;
} else {
-1
}
}
/* Driver Code */

View File

@ -7,11 +7,17 @@
/* 编辑距离:暴力搜索 */
fn edit_distance_dfs(s: &str, t: &str, i: usize, j: usize) -> i32 {
// 若 s 和 t 都为空,则返回 0
if i == 0 && j == 0 { return 0; }
if i == 0 && j == 0 {
return 0;
}
// 若 s 为空,则返回 t 长度
if i == 0 { return j as i32; }
if i == 0 {
return j as i32;
}
// 若 t 为空,则返回 s 长度
if j == 0 {return i as i32; }
if j == 0 {
return i as i32;
}
// 若两字符相等,则直接跳过此两字符
if s.chars().nth(i - 1) == t.chars().nth(j - 1) {
return edit_distance_dfs(s, t, i - 1, j - 1);
@ -27,13 +33,21 @@ fn edit_distance_dfs(s: &str, t: &str, i: usize, j: usize) -> i32 {
/* 编辑距离:记忆化搜索 */
fn edit_distance_dfs_mem(s: &str, t: &str, mem: &mut Vec<Vec<i32>>, i: usize, j: usize) -> i32 {
// 若 s 和 t 都为空,则返回 0
if i == 0 && j == 0 { return 0; }
if i == 0 && j == 0 {
return 0;
}
// 若 s 为空,则返回 t 长度
if i == 0 { return j as i32; }
if i == 0 {
return j as i32;
}
// 若 t 为空,则返回 s 长度
if j == 0 {return i as i32; }
if j == 0 {
return i as i32;
}
// 若已有记录,则直接返回之
if mem[i][j] != -1 { return mem[i][j]; }
if mem[i][j] != -1 {
return mem[i][j];
}
// 若两字符相等,则直接跳过此两字符
if s.chars().nth(i - 1) == t.chars().nth(j - 1) {
return edit_distance_dfs_mem(s, t, mem, i - 1, j - 1);
@ -66,7 +80,8 @@ fn edit_distance_dp(s: &str, t: &str) -> i32 {
dp[i][j] = dp[i - 1][j - 1];
} else {
// 最少编辑步数 = 插入、删除、替换这三种操作的最少编辑步数 + 1
dp[i][j] = std::cmp::min(std::cmp::min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
dp[i][j] =
std::cmp::min(std::cmp::min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
}
}
}

View File

@ -56,7 +56,10 @@ fn knapsack_dp(wgt: &[i32], val: &[i32], cap: usize) -> i32 {
dp[i][c] = dp[i - 1][c];
} else {
// 不选和选物品 i 这两种方案的较大值
dp[i][c] = std::cmp::max(dp[i - 1][c], dp[i - 1][c - wgt[i - 1] as usize] + val[i - 1]);
dp[i][c] = std::cmp::max(
dp[i - 1][c],
dp[i - 1][c - wgt[i - 1] as usize] + val[i - 1],
);
}
}
}

View File

@ -9,7 +9,9 @@ use std::cmp;
/* 爬楼梯最小代价:动态规划 */
fn min_cost_climbing_stairs_dp(cost: &[i32]) -> i32 {
let n = cost.len() - 1;
if n == 1 || n == 2 { return cost[n]; }
if n == 1 || n == 2 {
return cost[n];
}
// 初始化 dp 表,用于存储子问题的解
let mut dp = vec![-1; n + 1];
// 初始状态:预设最小子问题的解
@ -25,7 +27,9 @@ fn min_cost_climbing_stairs_dp(cost: &[i32]) -> i32 {
/* 爬楼梯最小代价:空间优化后的动态规划 */
fn min_cost_climbing_stairs_dp_comp(cost: &[i32]) -> i32 {
let n = cost.len() - 1;
if n == 1 || n == 2 { return cost[n] };
if n == 1 || n == 2 {
return cost[n];
};
let (mut a, mut b) = (cost[1], cost[2]);
for i in 3..=n {
let tmp = b;

View File

@ -94,7 +94,8 @@ pub fn main() {
vec![1, 3, 1, 5],
vec![2, 2, 4, 2],
vec![5, 3, 2, 1],
vec![ 4, 3, 5, 2 ]];
vec![4, 3, 5, 2],
];
let (n, m) = (grid.len(), grid[0].len());
// 暴力搜索

View File

@ -6,9 +6,9 @@
mod graph_adjacency_list;
use std::collections::{HashSet, VecDeque};
use graph_adjacency_list::GraphAdjList;
use graph_adjacency_list::{Vertex, vets_to_vals, vals_to_vets};
use graph_adjacency_list::{vals_to_vets, vets_to_vals, Vertex};
use std::collections::{HashSet, VecDeque};
/* 广度优先遍历 */
// 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点
@ -25,6 +25,7 @@ fn graph_bfs(graph: GraphAdjList, start_vet: Vertex) -> Vec<Vertex> {
while !que.is_empty() {
let vet = que.pop_front().unwrap(); // 队首顶点出队
res.push(vet); // 记录访问顶点
// 遍历该顶点的所有邻接顶点
if let Some(adj_vets) = graph.adj_list.get(&vet) {
for &adj_vet in adj_vets {

View File

@ -6,9 +6,9 @@
mod graph_adjacency_list;
use std::collections::HashSet;
use graph_adjacency_list::GraphAdjList;
use graph_adjacency_list::{Vertex, vets_to_vals, vals_to_vets};
use graph_adjacency_list::{vals_to_vets, vets_to_vals, Vertex};
use std::collections::HashSet;
/* 深度优先遍历辅助函数 */
fn dfs(graph: &GraphAdjList, visited: &mut HashSet<Vertex>, res: &mut Vec<Vertex>, vet: Vertex) {

View File

@ -12,13 +12,15 @@ pub struct Pair {
}
/* 基于数组实现的哈希表 */
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],
}
}
/* 哈希函数 */
@ -50,17 +52,26 @@ impl ArrayHashMap {
/* 获取所有键值对 */
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

@ -151,10 +151,13 @@ pub fn main() {
/* 查询操作 */
// 向哈希表中输入键 key ,得到值 value
println!("\n输入学号 13276,查询到姓名 {}", match map.get(13276) {
println!(
"\n输入学号 13276,查询到姓名 {}",
match map.get(13276) {
Some(value) => value,
None => "Not a valid Key"
});
None => "Not a valid Key",
}
);
/* 删除操作 */
// 在哈希表中删除键值对 (key, value)

View File

@ -20,7 +20,6 @@ struct HashMapOpenAddressing {
TOMBSTONE: Option<Pair>, // 删除标记
}
impl HashMapOpenAddressing {
/* 构造方法 */
fn new() -> Self {
@ -30,7 +29,10 @@ impl HashMapOpenAddressing {
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(),
}),
}
}
@ -68,7 +70,11 @@ impl HashMapOpenAddressing {
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

@ -4,7 +4,6 @@
* Author: night-cruise (2586447362@qq.com)
*/
/* 加法哈希 */
fn add_hash(key: &str) -> i32 {
let mut hash = 0_i64;

View File

@ -12,11 +12,14 @@ fn binary_search(nums: &[i32], target: i32) -> i32 {
// 循环,当搜索区间为空时跳出(当 i > j 时为空)
while i <= j {
let m = i + (j - i) / 2; // 计算中点索引 m
if nums[m as usize] < target { // 此情况说明 target 在区间 [m+1, j] 中
if nums[m as usize] < target {
// 此情况说明 target 在区间 [m+1, j] 中
i = m + 1;
} else if nums[m as usize] > target { // 此情况说明 target 在区间 [i, m-1] 中
} else if nums[m as usize] > target {
// 此情况说明 target 在区间 [i, m-1] 中
j = m - 1;
} else { // 找到目标元素,返回其索引
} else {
// 找到目标元素,返回其索引
return m;
}
}
@ -32,11 +35,14 @@ fn binary_search_lcro(nums: &[i32], target: i32) -> i32 {
// 循环,当搜索区间为空时跳出(当 i = j 时为空)
while i < j {
let m = i + (j - i) / 2; // 计算中点索引 m
if nums[m as usize] < target { // 此情况说明 target 在区间 [m+1, j) 中
if nums[m as usize] < target {
// 此情况说明 target 在区间 [m+1, j) 中
i = m + 1;
} else if nums[m as usize] > target { // 此情况说明 target 在区间 [i, m) 中
} else if nums[m as usize] > target {
// 此情况说明 target 在区间 [i, m) 中
j = m;
} else { // 找到目标元素,返回其索引
} else {
// 找到目标元素,返回其索引
return m;
}
}

View File

@ -8,7 +8,6 @@ mod binary_search_insertion;
use binary_search_insertion::binary_search_insertion;
/* 二分查找最左一个 target */
fn binary_search_left_edge(nums: &[i32], target: i32) -> i32 {
// 等价于查找 target 的插入点

View File

@ -39,7 +39,6 @@ pub fn binary_search_insertion(nums: &[i32], target: i32) -> i32 {
i
}
/* Driver Code */
fn main() {
// 无重复元素的数组

View File

@ -6,10 +6,10 @@
include!("../include/include.rs");
use list_node::ListNode;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::cell::RefCell;
use list_node::ListNode;
/* 哈希查找(数组) */
fn hashing_search_array<'a>(map: &'a HashMap<i32, usize>, target: i32) -> Option<&'a usize> {
@ -19,7 +19,10 @@ fn hashing_search_array<'a>(map: &'a HashMap<i32, usize>, target: i32) -> Option
}
/* 哈希查找(链表) */
fn hashing_search_linked_list(map: &HashMap<i32, Rc<RefCell<ListNode<i32>>>>, target: i32) -> Option<&Rc<RefCell<ListNode<i32>>>> {
fn hashing_search_linked_list(
map: &HashMap<i32, Rc<RefCell<ListNode<i32>>>>,
target: i32,
) -> Option<&Rc<RefCell<ListNode<i32>>>> {
// 哈希表的 key: 目标节点值value: 节点对象
// 若哈希表中无此 key ,返回 None
map.get(&target)

View File

@ -6,9 +6,9 @@
include!("../include/include.rs");
use std::rc::Rc;
use std::cell::RefCell;
use list_node::ListNode;
use std::cell::RefCell;
use std::rc::Rc;
/* 线性查找(数组) */
fn linear_search_array(nums: &[i32], target: i32) -> i32 {
@ -24,9 +24,14 @@ fn linear_search_array(nums: &[i32], target: i32) -> i32 {
}
/* 线性查找(链表) */
fn linear_search_linked_list(head: Rc<RefCell<ListNode<i32>>>, target: i32) -> Option<Rc<RefCell<ListNode<i32>>>> {
fn linear_search_linked_list(
head: Rc<RefCell<ListNode<i32>>>,
target: i32,
) -> Option<Rc<RefCell<ListNode<i32>>>> {
// 找到目标节点,返回之
if head.borrow().val == target {return Some(head)};
if head.borrow().val == target {
return Some(head);
};
// 找到目标节点,返回之
if let Some(node) = &head.borrow_mut().next {
return linear_search_linked_list(node.clone(), target);

View File

@ -30,7 +30,7 @@ pub fn two_sum_hash_table(nums: &Vec<i32>, target: i32) -> Option<Vec<i32>> {
for (i, num) in nums.iter().enumerate() {
match dic.get(&(target - num)) {
Some(v) => return Some(vec![*v as i32, i as i32]),
None => dic.insert(num, i as i32)
None => dic.insert(num, i as i32),
};
}
None

View File

@ -27,6 +27,7 @@ fn bubble_sort_with_flag(nums: &mut [i32]) {
// 外循环:未排序区间为 [0, i]
for i in (1..nums.len()).rev() {
let mut flag = false; // 初始化标志位
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
for j in 0..i {
if nums[j] > nums[j + 1] {
@ -37,7 +38,9 @@ fn bubble_sort_with_flag(nums: &mut [i32]) {
flag = true; // 记录交换元素
}
}
if !flag {break}; // 此轮“冒泡”未交换任何元素,直接跳出
if !flag {
break; // 此轮“冒泡”未交换任何元素,直接跳出
};
}
}

View File

@ -43,11 +43,15 @@ fn merge(nums: &mut [i32], left: usize, mid: usize, right: usize) {
/* 归并排序 */
fn merge_sort(nums: &mut [i32], left: usize, right: usize) {
// 终止条件
if left >= right { return; } // 当子数组长度为 1 时终止递归
if left >= right {
return; // 当子数组长度为 1 时终止递归
}
// 划分阶段
let mid = (left + right) / 2; // 计算中点
merge_sort(nums, left, mid); // 递归左子数组
merge_sort(nums, mid + 1, right); // 递归右子数组
// 合并阶段
merge(nums, left, mid, right);
}

View File

@ -4,7 +4,6 @@
* Author: xBLACKICEx (xBLACKICE@outlook.com)
*/
/* 快速排序 */
struct QuickSort;

View File

@ -50,7 +50,7 @@ impl ArrayDeque {
pub fn push_first(&mut self, num: i32) {
if self.que_size == self.capacity() {
println!("双向队列已满");
return
return;
}
// 队首指针向左移动一位
// 通过取余操作实现 front 越过数组头部后回到尾部
@ -64,7 +64,7 @@ impl ArrayDeque {
pub fn push_last(&mut self, num: i32) {
if self.que_size == self.capacity() {
println!("双向队列已满");
return
return;
}
// 计算队尾指针,指向队尾索引 + 1
let rear = self.index(self.front as i32 + self.que_size as i32);
@ -91,13 +91,17 @@ impl ArrayDeque {
/* 访问队首元素 */
fn peek_first(&self) -> i32 {
if self.is_empty() { panic!("双向队列为空") };
if self.is_empty() {
panic!("双向队列为空")
};
self.nums[self.front]
}
/* 访问队尾元素 */
fn peek_last(&self) -> i32 {
if self.is_empty() { panic!("双向队列为空") };
if self.is_empty() {
panic!("双向队列为空")
};
// 计算尾元素索引
let last = self.index(self.front as i32 + self.que_size as i32 - 1);
self.nums[last]

View File

@ -14,7 +14,9 @@ struct ArrayStack<T> {
impl<T> ArrayStack<T> {
/* 初始化栈 */
fn new() -> ArrayStack<T> {
ArrayStack::<T> { stack: Vec::<T>::new() }
ArrayStack::<T> {
stack: Vec::<T>::new(),
}
}
/* 获取栈的长度 */
@ -42,7 +44,9 @@ impl<T> ArrayStack<T> {
/* 访问栈顶元素 */
fn peek(&self) -> Option<&T> {
if self.is_empty() { panic!("栈为空") };
if self.is_empty() {
panic!("栈为空")
};
self.stack.last()
}

View File

@ -6,8 +6,8 @@
include!("../include/include.rs");
use std::rc::Rc;
use std::cell::RefCell;
use std::rc::Rc;
/* 双向链表节点 */
pub struct ListNode<T> {
@ -105,7 +105,7 @@ impl<T: Copy> LinkedListDeque<T> {
pub fn pop(&mut self, is_front: bool) -> Option<T> {
// 若队列为空,直接返回 None
if self.is_empty() {
return None
return None;
};
// 队首出队操作
if is_front {
@ -122,7 +122,6 @@ impl<T: Copy> LinkedListDeque<T> {
self.que_size -= 1; // 更新队列长度
Rc::try_unwrap(old_front).ok().unwrap().into_inner().val
})
}
// 队尾出队操作
else {

View File

@ -6,9 +6,9 @@
include!("../include/include.rs");
use std::rc::Rc;
use std::cell::RefCell;
use list_node::ListNode;
use std::cell::RefCell;
use std::rc::Rc;
/* 基于链表实现的队列 */
#[allow(dead_code)]

View File

@ -6,9 +6,9 @@
include!("../include/include.rs");
use std::rc::Rc;
use std::cell::RefCell;
use list_node::ListNode;
use std::cell::RefCell;
use std::rc::Rc;
/* 基于链表实现的栈 */
#[allow(dead_code)]

View File

@ -6,10 +6,10 @@
include!("../include/include.rs");
use tree_node::TreeNode;
use std::rc::Rc;
use std::cmp::Ordering;
use std::cell::RefCell;
use std::cmp::Ordering;
use std::rc::Rc;
use tree_node::TreeNode;
type OptionTreeNodeRc = Option<Rc<RefCell<TreeNode>>>;
@ -157,6 +157,7 @@ impl AVLTree {
}
}
Self::update_height(Some(node.clone())); // 更新节点高度
/* 2. 执行旋转操作,使该子树重新恢复平衡 */
node = Self::rotate(Some(node)).unwrap();
// 返回子树的根节点
@ -211,6 +212,7 @@ impl AVLTree {
node.borrow_mut().val = temp.borrow().val;
}
Self::update_height(Some(node.clone())); // 更新节点高度
/* 2. 执行旋转操作,使该子树重新恢复平衡 */
node = Self::rotate(Some(node)).unwrap();
// 返回子树的根节点

View File

@ -7,8 +7,8 @@
include!("../include/include.rs");
use std::cell::RefCell;
use std::rc::Rc;
use std::cmp::Ordering;
use std::rc::Rc;
use tree_node::TreeNode;
@ -171,7 +171,11 @@ fn main() {
/* 查找结点 */
let node = bst.search(7);
println!("\n查找到的节点对象为 {:?},节点值 = {}", node.clone().unwrap(), node.clone().unwrap().borrow().val);
println!(
"\n查找到的节点对象为 {:?},节点值 = {}",
node.clone().unwrap(),
node.clone().unwrap().borrow().val
);
/* 插入节点 */
bst.insert(16);

View File

@ -3,7 +3,6 @@
* Created Time: 2023-02-27
* Author: xBLACKICEx (xBLACKICE@outlook.com)
*/
use std::rc::Rc;
include!("../include/include.rs");
use tree_node::TreeNode;

View File

@ -18,7 +18,8 @@ fn level_order(root: &Rc<RefCell<TreeNode>>) -> Vec<i32> {
// 初始化一个列表,用于保存遍历序列
let mut vec = Vec::new();
while let Some(node) = que.pop_front() { // 队列出队
while let Some(node) = que.pop_front() {
// 队列出队
vec.push(node.borrow().val); // 保存节点值
if let Some(left) = node.borrow().left.as_ref() {
que.push_back(Rc::clone(left)); // 左子节点入队