This commit is contained in:
krahets
2024-03-25 22:43:12 +08:00
parent 22017aa8e5
commit 87af663929
70 changed files with 7428 additions and 32 deletions
+23
View File
@@ -411,6 +411,29 @@ comments: true
}
```
=== "Kotlin"
```kotlin title="top_k.kt"
/* 基于堆查找数组中最大的 k 个元素 */
fun topKHeap(nums: IntArray, k: Int): Queue<Int> {
// 初始化小顶堆
val heap = PriorityQueue<Int>()
// 将数组的前 k 个元素入堆
for (i in 0..<k) {
heap.offer(nums[i])
}
// 从第 k+1 个元素开始,保持堆的长度为 k
for (i in k..<nums.size) {
// 若当前元素大于堆顶元素,则将堆顶元素出堆、当前元素入堆
if (nums[i] > heap.peek()) {
heap.poll()
heap.offer(nums[i])
}
}
return heap
}
```
=== "Zig"
```zig title="top_k.zig"