mirror of
https://github.com/krahets/hello-algo.git
synced 2026-04-27 12:01:49 +08:00
* Review the EN heading format. * Fix pythontutor headings. * Fix pythontutor headings. * bug fixes * Fix headings in **/summary.md * Revisit the CN-to-EN translation for Python code using Claude-4.5 * Revisit the CN-to-EN translation for Java code using Claude-4.5 * Revisit the CN-to-EN translation for Cpp code using Claude-4.5. * Fix the dictionary. * Fix cpp code translation for the multipart strings. * Translate Go code to English. * Update workflows to test EN code. * Add EN translation for C. * Add EN translation for CSharp. * Add EN translation for Swift. * Trigger the CI check. * Revert. * Update en/hash_map.md * Add the EN version of Dart code. * Add the EN version of Kotlin code. * Add missing code files. * Add the EN version of JavaScript code. * Add the EN version of TypeScript code. * Fix the workflows. * Add the EN version of Ruby code. * Add the EN version of Rust code. * Update the CI check for the English version code. * Update Python CI check. * Fix cmakelists for en/C code. * Fix Ruby comments
40 lines
1.2 KiB
Rust
40 lines
1.2 KiB
Rust
/*
|
|
* File: top_k.rs
|
|
* Created Time: 2023-07-16
|
|
* Author: night-cruise (2586447362@qq.com)
|
|
*/
|
|
|
|
use hello_algo_rust::include::print_util;
|
|
|
|
use std::cmp::Reverse;
|
|
use std::collections::BinaryHeap;
|
|
|
|
/* Find the largest k elements in array based on heap */
|
|
fn top_k_heap(nums: Vec<i32>, k: usize) -> BinaryHeap<Reverse<i32>> {
|
|
// BinaryHeap is a max heap, use Reverse to negate elements to implement min heap
|
|
let mut heap = BinaryHeap::<Reverse<i32>>::new();
|
|
// Enter the first k elements of array into heap
|
|
for &num in nums.iter().take(k) {
|
|
heap.push(Reverse(num));
|
|
}
|
|
// Starting from the (k+1)th element, maintain heap length as k
|
|
for &num in nums.iter().skip(k) {
|
|
// If current element is greater than top element, top element exits heap, current element enters heap
|
|
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!("The largest {} elements are", k);
|
|
print_util::print_heap(res.into_iter().map(|item| item.0).collect());
|
|
}
|