-
Notifications
You must be signed in to change notification settings - Fork 12.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feature(swift): Reimplement merge_sort and top_k (#898)
* feat: Add swift-collections * fix: use heap * refactor: merge * fix: import HeapModule
- Loading branch information
Showing
4 changed files
with
52 additions
and
33 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
{ | ||
"pins" : [ | ||
{ | ||
"identity" : "swift-collections", | ||
"kind" : "remoteSourceControl", | ||
"location" : "https://github.com/apple/swift-collections", | ||
"state" : { | ||
"branch" : "release/1.1", | ||
"revision" : "4a1d92ba85027010d2c528c05576cde9a362254b" | ||
} | ||
} | ||
], | ||
"version" : 2 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,21 +4,22 @@ | |
* Author: nuomi1 ([email protected]) | ||
*/ | ||
|
||
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 | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters