mirror of
https://github.com/krahets/hello-algo.git
synced 2026-04-24 18:43:59 +08:00
Review Swift codes (#1150)
* feat(swift): review for chapter_computational_complexity * feat(swift): review for chapter_data_structure * feat(swift): review for chapter_array_and_linkedlist * feat(swift): review for chapter_stack_and_queue * feat(swift): review for chapter_hashing * feat(swift): review for chapter_tree * feat(swift): add codes for heap article * feat(swift): review for chapter_heap * feat(swift): review for chapter_graph * feat(swift): review for chapter_searching * feat(swift): review for chapter_sorting * feat(swift): review for chapter_divide_and_conquer * feat(swift): review for chapter_backtracking * feat(swift): review for chapter_dynamic_programming * feat(swift): review for chapter_greedy * feat(swift): review for utils * feat(swift): update ci tool * feat(swift): trailing closure * feat(swift): array init * feat(swift): map index
This commit is contained in:
@@ -270,7 +270,35 @@
|
||||
=== "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"
|
||||
|
||||
Reference in New Issue
Block a user