hello-algo/codes/swift/chapter_heap/top_k.swift

35 lines
887 B
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* File: top_k.swift
* Created Time: 2023-07-02
* Author: nuomi1 (nuomi1@qq.com)
*/
import utils
/* 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
}
@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)
}
}