diff --git a/codes/rust/Cargo.toml b/codes/rust/Cargo.toml index 4923d9ecb..86b27111b 100644 --- a/codes/rust/Cargo.toml +++ b/codes/rust/Cargo.toml @@ -179,6 +179,41 @@ path = "chapter_tree/binary_tree_dfs.rs" name = "binary_tree" path = "chapter_tree/binary_tree.rs" +# Run Command: cargo run --bin heap +[[bin]] +name = "heap" +path = "chapter_heap/heap.rs" + +# Run Command: cargo run --bin my_heap +[[bin]] +name = "my_heap" +path = "chapter_heap/my_heap.rs" + +# Run Command: cargo run --bin top_k +[[bin]] +name = "top_k" +path = "chapter_heap/top_k.rs" + +# Run Command: cargo run --bin graph_adjacency_list +[[bin]] +name = "graph_adjacency_list" +path = "chapter_graph/graph_adjacency_list.rs" + +# Run Command: cargo run --bin graph_adjacency_matrix +[[bin]] +name = "graph_adjacency_matrix" +path = "chapter_graph/graph_adjacency_matrix.rs" + +# Run Command: cargo run --bin graph_bfs +[[bin]] +name = "graph_bfs" +path = "chapter_graph/graph_bfs.rs" + +# Run Command: cargo run --bin graph_dfs +[[bin]] +name = "graph_dfs" +path = "chapter_graph/graph_dfs.rs" + # Run Command: cargo run --bin linear_search [[bin]] name = "linear_search" @@ -234,26 +269,6 @@ path = "chapter_backtracking/subset_sum_i.rs" name = "subset_sum_ii" path = "chapter_backtracking/subset_sum_ii.rs" -# Run Command: cargo run --bin graph_adjacency_list -[[bin]] -name = "graph_adjacency_list" -path = "chapter_graph/graph_adjacency_list.rs" - -# Run Command: cargo run --bin graph_adjacency_matrix -[[bin]] -name = "graph_adjacency_matrix" -path = "chapter_graph/graph_adjacency_matrix.rs" - -# Run Command: cargo run --bin graph_bfs -[[bin]] -name = "graph_bfs" -path = "chapter_graph/graph_bfs.rs" - -# Run Command: cargo run --bin graph_dfs -[[bin]] -name = "graph_dfs" -path = "chapter_graph/graph_dfs.rs" - # Run Command: cargo run --bin coin_change [[bin]] name = "coin_change" diff --git a/codes/rust/chapter_heap/heap.rs b/codes/rust/chapter_heap/heap.rs new file mode 100644 index 000000000..f81e127ca --- /dev/null +++ b/codes/rust/chapter_heap/heap.rs @@ -0,0 +1,73 @@ +/* + * File: heap.rs + * Created Time: 2023-07-16 + * Author: night-cruise (2586447362@qq.com) + */ + +include!("../include/include.rs"); + +use std::collections::BinaryHeap; + +fn test_push(heap: &mut BinaryHeap, val: i32, flag: i32) { + heap.push(flag * val); // 元素入堆 + println!("\n元素 {} 入堆后", val); + print_util::print_heap(heap.iter().map(|&val| flag * val).collect()); +} + +fn test_pop(heap: &mut BinaryHeap, flag: i32) { + let val = heap.pop().unwrap(); + println!("\n堆顶元素 {} 出堆后", flag * val); + print_util::print_heap(heap.iter().map(|&val| flag * val).collect()); +} + +/* Driver Code */ +fn main() { + /* 初始化堆 */ + // 初始化小顶堆 + #[allow(unused_assignments)] + let mut min_heap = BinaryHeap::new(); + // Rust 的 BinaryHeap 是大顶堆,当入队时将元素值乘以 -1 将其反转,当出队时将元素值乘以 -1 将其还原 + let min_heap_flag = -1; + // 初始化大顶堆 + let mut max_heap = BinaryHeap::new(); + let max_heap_flag = 1; + + println!("\n以下测试样例为大顶堆"); + + /* 元素入堆 */ + test_push(&mut max_heap, 1, max_heap_flag); + test_push(&mut max_heap, 3, max_heap_flag); + test_push(&mut max_heap, 2, max_heap_flag); + test_push(&mut max_heap, 5, max_heap_flag); + test_push(&mut max_heap, 4, max_heap_flag); + + /* 获取堆顶元素 */ + let peek = max_heap.peek().unwrap() * max_heap_flag; + println!("\n堆顶元素为 {}", peek); + + /* 堆顶元素出堆 */ + test_pop(&mut max_heap, max_heap_flag); + test_pop(&mut max_heap, max_heap_flag); + test_pop(&mut max_heap, max_heap_flag); + test_pop(&mut max_heap, max_heap_flag); + test_pop(&mut max_heap, max_heap_flag); + + /* 获取堆大小 */ + let size = max_heap.len(); + println!("\n堆元素数量为 {}", size); + + /* 判断堆是否为空 */ + let is_empty = max_heap.is_empty(); + println!("\n堆是否为空 {}", is_empty); + + /* 输入列表并建堆 */ + // 时间复杂度为 O(n) ,而非 O(nlogn) + min_heap = BinaryHeap::from( + vec![1, 3, 2, 5, 4] + .into_iter() + .map(|val| min_heap_flag * val) + .collect::>(), + ); + println!("\n输入列表并建立小顶堆后"); + print_util::print_heap(min_heap.iter().map(|&val| min_heap_flag * val).collect()); +} \ No newline at end of file diff --git a/codes/rust/chapter_heap/my_heap.rs b/codes/rust/chapter_heap/my_heap.rs new file mode 100644 index 000000000..80f624b5b --- /dev/null +++ b/codes/rust/chapter_heap/my_heap.rs @@ -0,0 +1,165 @@ +/* + * File: my_heap.rs + * Created Time: 2023-07-16 + * Author: night-cruise (2586447362@qq.com) + */ + +include!("../include/include.rs"); + +/* 大顶堆 */ +struct MaxHeap { + // 使用 vector 而非数组,这样无需考虑扩容问题 + max_heap: Vec, +} + +impl MaxHeap { + /* 构造方法,根据输入列表建堆 */ + fn new(nums: Vec) -> Self { + // 将列表元素原封不动添加进堆 + let mut heap = MaxHeap { max_heap: nums }; + // 堆化除叶节点以外的其他所有节点 + for i in (0..=Self::parent(heap.size() - 1)).rev() { + heap.sift_down(i); + } + heap + } + + /* 获取左子节点索引 */ + fn left(i: usize) -> usize { + 2 * i + 1 + } + + /* 获取右子节点索引 */ + fn right(i: usize) -> usize { + 2 * i + 2 + } + + /* 获取父节点索引 */ + fn parent(i: usize) -> usize { + (i - 1) / 2 // 向下整除 + } + + /* 交换元素 */ + fn swap(&mut self, i: usize, j: usize) { + self.max_heap.swap(i, j); + } + + /* 获取堆大小 */ + fn size(&self) -> usize { + self.max_heap.len() + } + + /* 判断堆是否为空 */ + fn is_empty(&self) -> bool { + self.max_heap.is_empty() + } + + /* 访问堆顶元素 */ + fn peek(&self) -> Option { + self.max_heap.first().copied() + } + + /* 元素入堆 */ + fn push(&mut self, val: i32) { + // 添加节点 + self.max_heap.push(val); + // 从底至顶堆化 + self.sift_up(self.size() - 1); + } + + /* 从节点 i 开始,从底至顶堆化 */ + fn sift_up(&mut self, mut i: usize) { + loop { + // 节点 i 已经是堆顶节点了,结束堆化 + if i == 0 { + break; + } + // 获取节点 i 的父节点 + let p = Self::parent(i); + // 当“节点无需修复”时,结束堆化 + if self.max_heap[i] <= self.max_heap[p] { + break; + } + // 交换两节点 + self.swap(i, p); + // 循环向上堆化 + i = p; + } + } + + /* 元素出堆 */ + fn pop(&mut self) -> i32 { + // 判空处理 + if self.is_empty() { + panic!("index out of bounds"); + } + // 交换根节点与最右叶节点(即交换首元素与尾元素) + self.swap(0, self.size() - 1); + // 删除节点 + let val = self.max_heap.remove(self.size() - 1); + // 从顶至底堆化 + self.sift_down(0); + // 返回堆顶元素 + val + } + + /* 从节点 i 开始,从顶至底堆化 */ + fn sift_down(&mut self, mut i: usize) { + loop { + // 判断节点 i, l, r 中值最大的节点,记为 ma + let (l, r, mut ma) = (Self::left(i), Self::right(i), i); + if l < self.size() && self.max_heap[l] > self.max_heap[ma] { + ma = l; + } + if r < self.size() && self.max_heap[r] > self.max_heap[ma] { + ma = r; + } + // 若节点 i 最大或索引 l, r 越界,则无需继续堆化,跳出 + if ma == i { + break; + } + // 交换两节点 + self.swap(i, ma); + // 循环向下堆化 + i = ma; + } + } + + /* 打印堆(二叉树) */ + fn print(&self) { + print_util::print_heap(self.max_heap.clone()); + } +} + +/* Driver Code */ +fn main() { + /* 初始化大顶堆 */ + let mut max_heap = MaxHeap::new(vec![9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2]); + println!("\n输入列表并建堆后"); + max_heap.print(); + + /* 获取堆顶元素 */ + let peek = max_heap.peek(); + if let Some(peek) = peek { + println!("\n堆顶元素为 {}", peek); + } + + /* 元素入堆 */ + let val = 7; + max_heap.push(val); + println!("\n元素 {} 入堆后", val); + max_heap.print(); + + /* 堆顶元素出堆 */ + let peek = max_heap.pop(); + println!("\n堆顶元素 {} 出堆后", peek); + max_heap.print(); + + /* 获取堆大小 */ + let size = max_heap.size(); + println!("\n堆元素数量为 {}", size); + + /* 判断堆是否为空 */ + let is_empty = max_heap.is_empty(); + println!("\n堆是否为空 {}", is_empty); +} \ No newline at end of file diff --git a/codes/rust/chapter_heap/top_k.rs b/codes/rust/chapter_heap/top_k.rs new file mode 100644 index 000000000..34579d2be --- /dev/null +++ b/codes/rust/chapter_heap/top_k.rs @@ -0,0 +1,39 @@ +/* + * File: top_k.rs + * Created Time: 2023-07-16 + * Author: night-cruise (2586447362@qq.com) + */ + +include!("../include/include.rs"); + +use std::cmp::Reverse; +use std::collections::BinaryHeap; + +/* 基于堆查找数组中最大的 k 个元素 */ +fn top_k_heap(nums: Vec, k: usize) -> BinaryHeap> { + // Rust 的 BinaryHeap 是大顶堆,使用 Reverse 将元素大小反转 + let mut heap = BinaryHeap::>::new(); + // 将数组的前 k 个元素入堆 + for &num in nums.iter().take(k) { + heap.push(Reverse(num)); + } + // 从第 k+1 个元素开始,保持堆的长度为 k + for &num in nums.iter().skip(k) { + // 若当前元素大于堆顶元素,则将堆顶元素出堆、当前元素入堆 + if num > heap.peek().unwrap().0 { + heap.pop(); + heap.push(Reverse(num)); + } + } + heap +} + +/* Driver Code */ +fn main() { + let nums = vec![1, 7, 6, 3, 2]; + let k = 3; + + let res = top_k_heap(nums, k); + println!("最大的 {} 个元素为", k); + print_util::print_heap(res.into_iter().map(|item| item.0).collect()); +} \ No newline at end of file diff --git a/codes/rust/include/print_util.rs b/codes/rust/include/print_util.rs index 0f11cdac2..01224ef43 100644 --- a/codes/rust/include/print_util.rs +++ b/codes/rust/include/print_util.rs @@ -10,7 +10,7 @@ use std::collections::{HashMap, VecDeque}; use std::rc::Rc; use crate::list_node::ListNode; -use crate::tree_node::TreeNode; +use crate::tree_node::{TreeNode, vec_to_tree}; struct Trunk<'a, 'b> { prev: Option<&'a Trunk<'a, 'b>>, @@ -90,3 +90,12 @@ fn show_trunks(trunk: Option<&Trunk>) { print!("{}", trunk.str.get()); } } + +/* Print a heap both in array and tree representations */ +pub fn print_heap(heap: Vec) { + println!("堆的数组表示:{:?}", heap); + println!("堆的树状表示:"); + if let Some(root) = vec_to_tree(heap.into_iter().map(|val| Some(val)).collect()) { + print_tree(&root); + } +} \ No newline at end of file