专题:堆

专题:堆

简介

  • 堆(heap)是一个基本数据结构, 其主要特征为堆顶元素为所有元素中的最大(大顶堆)或最小(小顶堆)元素;
  • 堆常用来解决 top-k 问题;

堆的基本操作

  • push(val):

  • pop()->val:

  • heapify()

堆的实现

Rust

  • rust 标准库中的堆结构为 BinaryHeap;
  • BinaryHeap默认为大顶堆;
  • 通过 Reverse来获取小顶堆;
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
use std::collections::BinaryHeap;
use std::cmp::Reverse;

let mut heap = BinaryHeap::new();

heap.push(10);
heap.push(3);
heap.push(18);

assert!(heap.len, 3);
assert!(heap.pop(), Some(18));
assert!(heap.len, 2);
assert!(heap.pop(), Some(10));
assert!(heap.len, 1);
assert!(heap.pop(), Some(3));
assert!(heap.len, 0);
assert!(heap.pop(), None);

heap.push(Reverse(10));
heap.push(Reverse(3));
heap.push(Reverse(18));

assert!(heap.len, 3);
assert!(heap.pop(), Some(Reverse(3)));
assert!(heap.len, 2);
assert!(heap.pop(), Some(Reverse(10)));
assert!(heap.len, 1);
assert!(heap.pop(), Some(Reverse(18)));
assert!(heap.len, 0);
assert!(heap.pop(), None);

堆排序

  • 利用堆顶为

相关题目

updatedupdated2024-05-052024-05-05