feature(swift): Reimplement merge_sort and top_k (#898)

* feat: Add swift-collections

* fix: use heap

* refactor: merge

* fix: import HeapModule
This commit is contained in:
nuomi1
2023-10-27 22:59:54 +08:00
committed by GitHub
parent ba74d4bba7
commit 7605cab160
4 changed files with 52 additions and 33 deletions
+6 -5
View File
@@ -4,21 +4,22 @@
* Author: nuomi1 (nuomi1@qq.com)
*/
import HeapModule
import utils
/* k */
func topKHeap(nums: [Int], k: Int) -> [Int] {
// k
var heap = Array(nums.prefix(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.first! {
heap.removeFirst()
heap.insert(nums[i], at: 0)
if nums[i] > heap.min()! {
_ = heap.removeMin()
heap.insert(nums[i])
}
}
return heap
return heap.unordered
}
@main