mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-24 03:56:28 +08:00
Add kotlin code block for chapter_heap (#1196)
* Add kotlin code block for chapter_hashing * Add kotlin code block for chapter_heap.
This commit is contained in:
parent
8a05edb604
commit
e799513173
1 changed files with 32 additions and 1 deletions
|
@ -368,7 +368,38 @@
|
|||
=== "Kotlin"
|
||||
|
||||
```kotlin title="heap.kt"
|
||||
|
||||
/* 初始化堆 */
|
||||
// 初始化小顶堆
|
||||
var minHeap = PriorityQueue<Int>()
|
||||
// 初始化大顶堆(使用 lambda 表达式修改 Comparator 即可)
|
||||
val maxHeap = PriorityQueue { a: Int, b: Int -> b - a }
|
||||
|
||||
/* 元素入堆 */
|
||||
maxHeap.offer(1)
|
||||
maxHeap.offer(3)
|
||||
maxHeap.offer(2)
|
||||
maxHeap.offer(5)
|
||||
maxHeap.offer(4)
|
||||
|
||||
/* 获取堆顶元素 */
|
||||
var peek = maxHeap.peek() // 5
|
||||
|
||||
/* 堆顶元素出堆 */
|
||||
// 出堆元素会形成一个从大到小的序列
|
||||
peek = maxHeap.poll() // 5
|
||||
peek = maxHeap.poll() // 4
|
||||
peek = maxHeap.poll() // 3
|
||||
peek = maxHeap.poll() // 2
|
||||
peek = maxHeap.poll() // 1
|
||||
|
||||
/* 获取堆大小 */
|
||||
val size = maxHeap.size
|
||||
|
||||
/* 判断堆是否为空 */
|
||||
val isEmpty = maxHeap.isEmpty()
|
||||
|
||||
/* 输入列表并建堆 */
|
||||
minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4))
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
|
Loading…
Reference in a new issue