use std::collections::BinaryHeap;
fn main() {
let nums = vec![4, 1, 7, 3, 8, 5];
let mut max_heap = BinaryHeap::from(nums);
let mut kth_largest = 0;
for _ in 0..3 {
kth_largest = max_heap.pop().unwrap();
}
println!("{}", kth_largest);
}The max heap built from the vector will have elements ordered so the largest is popped first.
Pop 1: 8 (largest), Pop 2: 7 (second largest), Pop 3: 5 (third largest).
So the output is 5.
A max heap always keeps the largest element at the root, so popping repeatedly removes the largest elements in order.
This makes it efficient to find the kth largest by popping k times.
use std::collections::BinaryHeap;
fn main() {
let nums = vec![10, 20, 15];
let mut max_heap = BinaryHeap::new();
for num in nums {
max_heap.push(num);
}
let mut kth_largest = 0;
for _ in 0..2 {
kth_largest = max_heap.pop().unwrap();
}
println!("{}", kth_largest);
}The code correctly builds a max heap by pushing all elements.
Popping twice removes 20 then 15, so kth_largest is 15.
Output is 15, no errors.
use std::collections::BinaryHeap;
fn main() {
let mut max_heap = BinaryHeap::new();
max_heap.push(2);
max_heap.push(9);
max_heap.push(4);
max_heap.push(7);
max_heap.pop();
max_heap.pop();
let mut result = Vec::new();
while let Some(val) = max_heap.pop() {
result.push(val);
}
println!("{:?}", result);
}Push order: 2,9,4,7
Heap max is 9, pop removes 9
Next max is 7, pop removes 7
Remaining elements are 4 and 2
Popping all remaining gives [4, 2]
use std::collections::BinaryHeap;
fn main() {
let nums = vec![12, 3, 5, 7, 19, 0, 8];
let mut max_heap = BinaryHeap::from(nums);
let mut kth_largest = 0;
for _ in 0..4 {
kth_largest = max_heap.pop().unwrap();
}
println!("{}", kth_largest);
}Heap elements: 19, 12, 8, 7, 5, 3, 0
Pop 1: 19
Pop 2: 12
Pop 3: 8
Pop 4: 7
The 4th largest element is 7.
