You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hello-algo/codes/swift/chapter_heap/top_k.swift

37 lines
930 B

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/**
* File: top_k.swift
* Created Time: 2023-07-02
* Author: nuomi1 (nuomi1@qq.com)
*/
import HeapModule
import utils
/* k */
func topKHeap(nums: [Int], k: Int) -> [Int] {
// k
var heap = Heap(nums.prefix(k))
// k+1 k
for i in stride(from: k, to: nums.count, by: 1) {
//
if nums[i] > heap.min()! {
_ = heap.removeMin()
heap.insert(nums[i])
}
}
return heap.unordered
}
@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)
}
}