mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-15 00:26:05 +00:00
feat: add top_k.c and refactor top_k.js (#889)
* Add top_k.c based on my_heap.c * Improve the implementation of top_k.js * Add a comment to top_k
This commit is contained in:
@@ -11,7 +11,7 @@ use std::collections::BinaryHeap;
|
||||
|
||||
/* 基于堆查找数组中最大的 k 个元素 */
|
||||
fn top_k_heap(nums: Vec<i32>, k: usize) -> BinaryHeap<Reverse<i32>> {
|
||||
// Rust 的 BinaryHeap 是大顶堆,使用 Reverse 将元素大小反转
|
||||
// BinaryHeap 是大顶堆,使用 Reverse 将元素取反,从而实现小顶堆
|
||||
let mut heap = BinaryHeap::<Reverse<i32>>::new();
|
||||
// 将数组的前 k 个元素入堆
|
||||
for &num in nums.iter().take(k) {
|
||||
|
||||
Reference in New Issue
Block a user