mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-16 16:56:06 +00:00
build
This commit is contained in:
+14
-1
@@ -169,7 +169,20 @@ comments: true
|
||||
=== "Swift"
|
||||
|
||||
```swift title="top_k.swift"
|
||||
[class]{}-[func]{topKHeap}
|
||||
/* 基于堆查找数组中最大的 k 个元素 */
|
||||
func topKHeap(nums: [Int], k: Int) -> [Int] {
|
||||
// 将数组的前 k 个元素入堆
|
||||
var heap = Array(nums.prefix(k))
|
||||
// 从第 k+1 个元素开始,保持堆的长度为 k
|
||||
for i in stride(from: k, to: nums.count, by: 1) {
|
||||
// 若当前元素大于堆顶元素,则将堆顶元素出堆、当前元素入堆
|
||||
if nums[i] > heap.first! {
|
||||
heap.removeFirst()
|
||||
heap.insert(nums[i], at: 0)
|
||||
}
|
||||
}
|
||||
return heap
|
||||
}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
Reference in New Issue
Block a user