2023-07-06 03:16:14 +08:00
|
|
|
|
/**
|
|
|
|
|
* File: top_k.swift
|
|
|
|
|
* Created Time: 2023-07-02
|
|
|
|
|
* Author: nuomi1 (nuomi1@qq.com)
|
|
|
|
|
*/
|
|
|
|
|
|
2023-10-27 22:59:54 +08:00
|
|
|
|
import HeapModule
|
2023-07-06 03:16:14 +08:00
|
|
|
|
import utils
|
|
|
|
|
|
|
|
|
|
/* 基于堆查找数组中最大的 k 个元素 */
|
|
|
|
|
func topKHeap(nums: [Int], k: Int) -> [Int] {
|
2023-10-29 00:09:54 +08:00
|
|
|
|
// 初始化一个小顶堆,并将前 k 个元素建堆
|
2023-10-27 22:59:54 +08:00
|
|
|
|
var heap = Heap(nums.prefix(k))
|
2023-07-06 03:16:14 +08:00
|
|
|
|
// 从第 k+1 个元素开始,保持堆的长度为 k
|
2024-03-20 21:15:39 +08:00
|
|
|
|
for i in nums.indices.dropFirst(k) {
|
2023-07-06 03:16:14 +08:00
|
|
|
|
// 若当前元素大于堆顶元素,则将堆顶元素出堆、当前元素入堆
|
2023-10-27 22:59:54 +08:00
|
|
|
|
if nums[i] > heap.min()! {
|
|
|
|
|
_ = heap.removeMin()
|
|
|
|
|
heap.insert(nums[i])
|
2023-07-06 03:16:14 +08:00
|
|
|
|
}
|
|
|
|
|
}
|
2023-10-27 22:59:54 +08:00
|
|
|
|
return heap.unordered
|
2023-07-06 03:16:14 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@main
|
|
|
|
|
enum TopK {
|
|
|
|
|
/* Driver Code */
|
|
|
|
|
static func main() {
|
|
|
|
|
let nums = [1, 7, 6, 3, 2]
|
|
|
|
|
let k = 3
|
|
|
|
|
|
|
|
|
|
let res = topKHeap(nums: nums, k: k)
|
|
|
|
|
print("最大的 \(k) 个元素为")
|
|
|
|
|
PrintUtil.printHeap(queue: res)
|
|
|
|
|
}
|
|
|
|
|
}
|