mirror of
https://github.com/krahets/hello-algo.git
synced 2025-12-19 07:17:54 +08:00
Add build script for Swift.
This commit is contained in:
@@ -665,22 +665,7 @@ $$
|
||||
=== "Swift"
|
||||
|
||||
```swift title="space_complexity.swift"
|
||||
/* 常数阶 */
|
||||
func constant(n: Int) {
|
||||
// 常量、变量、对象占用 O(1) 空间
|
||||
let a = 0
|
||||
var b = 0
|
||||
let nums = Array(repeating: 0, count: 10000)
|
||||
let node = ListNode(x: 0)
|
||||
// 循环中的变量占用 O(1) 空间
|
||||
for _ in 0 ..< n {
|
||||
let c = 0
|
||||
}
|
||||
// 循环中的函数占用 O(1) 空间
|
||||
for _ in 0 ..< n {
|
||||
function()
|
||||
}
|
||||
}
|
||||
[class]{}-[func]{constant}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
@@ -797,15 +782,7 @@ $$
|
||||
=== "Swift"
|
||||
|
||||
```swift title="space_complexity.swift"
|
||||
/* 线性阶 */
|
||||
func linear(n: Int) {
|
||||
// 长度为 n 的数组占用 O(n) 空间
|
||||
let nums = Array(repeating: 0, count: n)
|
||||
// 长度为 n 的列表占用 O(n) 空间
|
||||
let nodes = (0 ..< n).map { ListNode(x: $0) }
|
||||
// 长度为 n 的哈希表占用 O(n) 空间
|
||||
let map = Dictionary(uniqueKeysWithValues: (0 ..< n).map { ($0, "\($0)") })
|
||||
}
|
||||
[class]{}-[func]{linear}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
@@ -901,14 +878,7 @@ $$
|
||||
=== "Swift"
|
||||
|
||||
```swift title="space_complexity.swift"
|
||||
/* 线性阶(递归实现) */
|
||||
func linearRecur(n: Int) {
|
||||
print("递归 n = \(n)")
|
||||
if n == 1 {
|
||||
return
|
||||
}
|
||||
linearRecur(n: n - 1)
|
||||
}
|
||||
[class]{}-[func]{linearRecur}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
@@ -1004,11 +974,7 @@ $$
|
||||
=== "Swift"
|
||||
|
||||
```swift title="space_complexity.swift"
|
||||
/* 平方阶 */
|
||||
func quadratic(n: Int) {
|
||||
// 二维列表占用 O(n^2) 空间
|
||||
let numList = Array(repeating: Array(repeating: 0, count: n), count: n)
|
||||
}
|
||||
[class]{}-[func]{quadratic}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
@@ -1100,15 +1066,7 @@ $$
|
||||
=== "Swift"
|
||||
|
||||
```swift title="space_complexity.swift"
|
||||
/* 平方阶(递归实现) */
|
||||
func quadraticRecur(n: Int) -> Int {
|
||||
if n <= 0 {
|
||||
return 0
|
||||
}
|
||||
// 数组 nums 长度为 n, n-1, ..., 2, 1
|
||||
let nums = Array(repeating: 0, count: n)
|
||||
return quadraticRecur(n: n - 1)
|
||||
}
|
||||
[class]{}-[func]{quadraticRecur}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
@@ -1199,16 +1157,7 @@ $$
|
||||
=== "Swift"
|
||||
|
||||
```swift title="space_complexity.swift"
|
||||
/* 指数阶(建立满二叉树) */
|
||||
func buildTree(n: Int) -> TreeNode? {
|
||||
if n == 0 {
|
||||
return nil
|
||||
}
|
||||
let root = TreeNode(x: 0)
|
||||
root.left = buildTree(n: n - 1)
|
||||
root.right = buildTree(n: n - 1)
|
||||
return root
|
||||
}
|
||||
[class]{}-[func]{buildTree}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
Reference in New Issue
Block a user