mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-26 22:42:41 +08:00
* Preserve the published Taiwan figure descriptions and homepage as editable sources * Update the five translated editions of Hello Algo * Fix reviewed translation, diagram, and example errors across the book * Correct Korean reader grammar, native diagnostics and example output
109 lines
2.3 KiB
Kotlin
109 lines
2.3 KiB
Kotlin
/**
|
||
* File: space_complexity.kt
|
||
* Created Time: 2024-01-25
|
||
* Author: curtishd (1023632660@qq.com)
|
||
*/
|
||
|
||
package chapter_computational_complexity.space_complexity
|
||
|
||
import utils.ListNode
|
||
import utils.TreeNode
|
||
import utils.printTree
|
||
|
||
/* 函式 */
|
||
fun function(): Int {
|
||
// 執行操作
|
||
return 0
|
||
}
|
||
|
||
/* 常數階 */
|
||
fun constant(n: Int) {
|
||
// 常數、變數、物件占用 O(1) 空間
|
||
val a = 0
|
||
var b = 0
|
||
val nums = Array(10000) { 0 }
|
||
val node = ListNode(0)
|
||
// 迴圈內變數占用 O(1) 空間
|
||
for (i in 0..<n) {
|
||
val c = 0
|
||
}
|
||
// 迴圈呼叫函式占用 O(1) 空間
|
||
for (i in 0..<n) {
|
||
function()
|
||
}
|
||
}
|
||
|
||
/* 線性階 */
|
||
fun linear(n: Int) {
|
||
// 長度為 n 的陣列占用 O(n) 空間
|
||
val nums = Array(n) { 0 }
|
||
// 長度為 n 的串列占用 O(n) 空間
|
||
val nodes = mutableListOf<ListNode>()
|
||
for (i in 0..<n) {
|
||
nodes.add(ListNode(i))
|
||
}
|
||
// 長度為 n 的雜湊表占用 O(n) 空間
|
||
val map = mutableMapOf<Int, String>()
|
||
for (i in 0..<n) {
|
||
map[i] = i.toString()
|
||
}
|
||
}
|
||
|
||
/* 線性階(遞迴實作) */
|
||
fun linearRecur(n: Int) {
|
||
println("遞迴 n = $n")
|
||
if (n == 1)
|
||
return
|
||
linearRecur(n - 1)
|
||
}
|
||
|
||
/* 平方階 */
|
||
fun quadratic(n: Int) {
|
||
// 矩陣占用 O(n^2) 空間
|
||
val numMatrix = arrayOfNulls<Array<Int>?>(n)
|
||
// 二維串列占用 O(n^2) 空間
|
||
val numList = mutableListOf<MutableList<Int>>()
|
||
for (i in 0..<n) {
|
||
val tmp = mutableListOf<Int>()
|
||
for (j in 0..<n) {
|
||
tmp.add(0)
|
||
}
|
||
numList.add(tmp)
|
||
}
|
||
}
|
||
|
||
/* 平方階(遞迴實作) */
|
||
tailrec fun quadraticRecur(n: Int): Int {
|
||
if (n <= 0)
|
||
return 0
|
||
// 陣列 nums 長度為 n, n-1, ..., 2, 1
|
||
val nums = Array(n) { 0 }
|
||
println("遞迴 n = $n 時,nums 的長度 = ${nums.size}")
|
||
return quadraticRecur(n - 1)
|
||
}
|
||
|
||
/* 指數階(建完美二元樹) */
|
||
fun buildTree(n: Int): TreeNode? {
|
||
if (n == 0)
|
||
return null
|
||
val root = TreeNode(0)
|
||
root.left = buildTree(n - 1)
|
||
root.right = buildTree(n - 1)
|
||
return root
|
||
}
|
||
|
||
/* 主程式 */
|
||
fun main() {
|
||
val n = 5
|
||
// 常數階
|
||
constant(n)
|
||
// 線性階
|
||
linear(n)
|
||
linearRecur(n)
|
||
// 平方階
|
||
quadratic(n)
|
||
quadraticRecur(n)
|
||
// 指數階
|
||
val root = buildTree(n)
|
||
printTree(root)
|
||
} |