【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());
}

总结

练习使用了标准库中的二叉堆。

附录

posted @   jiangbo4444  阅读(100)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2020-07-30 【JavaScript】标准内置变量 undefined
点击右上角即可分享
微信分享提示