This commit is contained in:
krahets
2024-03-21 04:22:07 +08:00
parent 35a07170c0
commit cfdb743939
52 changed files with 292 additions and 290 deletions

View File

@ -105,7 +105,7 @@ comments: true
// 将列表元素原封不动添加进堆
maxHeap = nums
// 堆化除叶节点以外的其他所有节点
for i in stride(from: parent(i: size() - 1), through: 0, by: -1) {
for i in (0 ... parent(i: size() - 1)).reversed() {
siftDown(i: i)
}
}

View File

@ -280,7 +280,35 @@ comments: true
=== "Swift"
```swift title="heap.swift"
// Swift 未提供内置 Heap 类
/* 初始化堆 */
// Swift 的 Heap 类型同时支持最大堆和最小堆,且需要引入 swift-collections
var heap = Heap<Int>()
/* 元素入堆 */
heap.insert(1)
heap.insert(3)
heap.insert(2)
heap.insert(5)
heap.insert(4)
/* 获取堆顶元素 */
var peek = heap.max()!
/* 堆顶元素出堆 */
peek = heap.removeMax() // 5
peek = heap.removeMax() // 4
peek = heap.removeMax() // 3
peek = heap.removeMax() // 2
peek = heap.removeMax() // 1
/* 获取堆大小 */
let size = heap.count
/* 判断堆是否为空 */
let isEmpty = heap.isEmpty
/* 输入列表并建堆 */
let heap2 = Heap([1, 3, 2, 5, 4])
```
=== "JS"

View File

@ -194,7 +194,7 @@ comments: true
// 初始化一个小顶堆,并将前 k 个元素建堆
var heap = Heap(nums.prefix(k))
// 从第 k+1 个元素开始,保持堆的长度为 k
for i in stride(from: k, to: nums.count, by: 1) {
for i in nums.indices.dropFirst(k) {
// 若当前元素大于堆顶元素,则将堆顶元素出堆、当前元素入堆
if nums[i] > heap.min()! {
_ = heap.removeMin()