【Rust】二叉堆-标准库
环境
- Time 2022-04-15
- Rust 1.60.0
前言
说明
基于标准库来学习各种数据结构,并不是从头实现数据结构,未考虑实现性能。
特点
二叉堆的极值在最前面,可能是最大值或者最小值,又叫大顶堆或者小顶堆。
示例
new
fn main() {
let mut heap = BinaryHeap::new();
heap.push(44);
}
push
fn main() {
let mut heap = BinaryHeap::new();
heap.push(44);
}
with_capacity
fn main() {
let mut heap = BinaryHeap::with_capacity(1);
heap.push(44);
println!("{heap:?}");
}
peek_mut
fn main() {
let mut heap = BinaryHeap::with_capacity(10);
(0..10).for_each(|e| heap.push(e));
println!("{heap:?}");
{
let mut max = heap.peek_mut().unwrap();
*max = -10;
}
println!("{heap:?}");
}
pop
fn main() {
let mut heap = BinaryHeap::with_capacity(10);
(0..10).for_each(|e| heap.push(e));
println!("{:?}", heap.pop());
println!("{heap:?}");
}
into_sorted_vec
fn main() {
let mut heap = BinaryHeap::with_capacity(10);
(0..10).for_each(|e| heap.push(e));
println!("{:?}", heap.into_sorted_vec());
}
into_vec
fn main() {
let mut heap = BinaryHeap::with_capacity(10);
(0..10).for_each(|e| heap.push(e));
println!("{:?}", heap.into_vec());
}
from
fn main() {
let mut heap = BinaryHeap::with_capacity(10);
(0..10).for_each(|e| heap.push(e));
heap.append(&mut BinaryHeap::from([3, 6, 9]));
println!("{:?}", heap);
}
append
fn main() {
let mut heap = BinaryHeap::with_capacity(10);
(0..10).for_each(|e| heap.push(e));
heap.append(&mut BinaryHeap::from([3, 6, 9]));
println!("{:?}", heap);
}
iter
fn main() {
let mut heap = BinaryHeap::with_capacity(10);
(0..10).for_each(|e| heap.push(e));
heap.iter().for_each(|e| println!("{e:?}"));
}
len
fn main() {
let mut heap = BinaryHeap::with_capacity(10);
(0..10).for_each(|e| heap.push(e));
println!("{:?}", heap.len());
}
is_empty
fn main() {
let mut heap = BinaryHeap::with_capacity(10);
(0..10).for_each(|e| heap.push(e));
println!("{:?}", heap.is_empty());
}
总结
练习使用了标准库中的二叉堆。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
2020-07-30 【JavaScript】标准内置变量 undefined