feat: add rust codes for chapter heap (#612)
Co-authored-by: Yudong Jin <krahets@163.com>pull/614/head
parent
ead33ca863
commit
a296786b2a
@ -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<i32>, 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<i32>, 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::<Vec<i32>>(),
|
||||
);
|
||||
println!("\n输入列表并建立小顶堆后");
|
||||
print_util::print_heap(min_heap.iter().map(|&val| min_heap_flag * val).collect());
|
||||
}
|
@ -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<i32>,
|
||||
}
|
||||
|
||||
impl MaxHeap {
|
||||
/* 构造方法,根据输入列表建堆 */
|
||||
fn new(nums: Vec<i32>) -> 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<i32> {
|
||||
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);
|
||||
}
|
@ -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<i32>, k: usize) -> BinaryHeap<Reverse<i32>> {
|
||||
// Rust 的 BinaryHeap 是大顶堆,使用 Reverse 将元素大小反转
|
||||
let mut heap = BinaryHeap::<Reverse<i32>>::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());
|
||||
}
|
Loading…
Reference in new issue