Merge pull request #197 from nuomi1/feature/space_complexity-Swift

feat: add Swift codes for space complexity article
pull/205/head
Yudong Jin 2 years ago committed by GitHub
commit 4ac254d1f7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -0,0 +1,130 @@
# Created by https://www.toptal.com/developers/gitignore/api/objective-c,swift,swiftpackagemanager
# Edit at https://www.toptal.com/developers/gitignore?templates=objective-c,swift,swiftpackagemanager
### Objective-C ###
# Xcode
#
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
## User settings
xcuserdata/
## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9)
*.xcscmblueprint
*.xccheckout
## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4)
build/
DerivedData/
*.moved-aside
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
## Obj-C/Swift specific
*.hmap
## App packaging
*.ipa
*.dSYM.zip
*.dSYM
# CocoaPods
# We recommend against adding the Pods directory to your .gitignore. However
# you should judge for yourself, the pros and cons are mentioned at:
# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
# Pods/
# Add this line if you want to avoid checking in source code from the Xcode workspace
# *.xcworkspace
# Carthage
# Add this line if you want to avoid checking in source code from Carthage dependencies.
# Carthage/Checkouts
Carthage/Build/
# fastlane
# It is recommended to not store the screenshots in the git repo.
# Instead, use fastlane to re-generate the screenshots whenever they are needed.
# For more information about the recommended setup visit:
# https://docs.fastlane.tools/best-practices/source-control/#source-control
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots/**/*.png
fastlane/test_output
# Code Injection
# After new code Injection tools there's a generated folder /iOSInjectionProject
# https://github.com/johnno1962/injectionforxcode
iOSInjectionProject/
### Objective-C Patch ###
### Swift ###
# Xcode
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
## Playgrounds
timeline.xctimeline
playground.xcworkspace
# Swift Package Manager
# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
# Packages/
# Package.pins
# Package.resolved
# *.xcodeproj
# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata
# hence it is not needed unless you have added a package configuration file to your project
# .swiftpm
.build/
# CocoaPods
# We recommend against adding the Pods directory to your .gitignore. However
# you should judge for yourself, the pros and cons are mentioned at:
# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
# Pods/
# Add this line if you want to avoid checking in source code from the Xcode workspace
# *.xcworkspace
# Carthage
# Add this line if you want to avoid checking in source code from Carthage dependencies.
# Carthage/Checkouts
# Accio dependency management
Dependencies/
.accio/
# fastlane
# It is recommended to not store the screenshots in the git repo.
# Instead, use fastlane to re-generate the screenshots whenever they are needed.
# For more information about the recommended setup visit:
# https://docs.fastlane.tools/best-practices/source-control/#source-control
# Code Injection
# After new code Injection tools there's a generated folder /iOSInjectionProject
# https://github.com/johnno1962/injectionforxcode
### SwiftPackageManager ###
Packages
xcuserdata
*.xcodeproj
# End of https://www.toptal.com/developers/gitignore/api/objective-c,swift,swiftpackagemanager

@ -0,0 +1,18 @@
// swift-tools-version: 5.7
import PackageDescription
let package = Package(
name: "HelloAlgo",
products: [
.executable(name: "time_complexity", targets: ["time_complexity"]),
.executable(name: "worst_best_time_complexity", targets: ["worst_best_time_complexity"]),
.executable(name: "space_complexity", targets: ["space_complexity"]),
],
targets: [
.target(name: "utils", path: "utils"),
.executableTarget(name: "time_complexity", path: "chapter_computational_complexity", sources: ["time_complexity.swift"]),
.executableTarget(name: "worst_best_time_complexity", path: "chapter_computational_complexity", sources: ["worst_best_time_complexity.swift"]),
.executableTarget(name: "space_complexity", dependencies: ["utils"], path: "chapter_computational_complexity", sources: ["space_complexity.swift"]),
]
)

@ -0,0 +1,98 @@
/*
* File: space_complexity.swift
* Created Time: 2023-01-01
* Author: nuomi1 (nuomi1@qq.com)
*/
import utils
//
@discardableResult
func function() -> Int {
// do something
return 0
}
//
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()
}
}
// 线
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)") })
}
// 线
func linearRecur(n: Int) {
print("递归 n = \(n)")
if n == 1 {
return
}
linearRecur(n: n - 1)
}
//
func quadratic(n: Int) {
// O(n^2)
let numList = Array(repeating: Array(repeating: 0, count: n), count: n)
}
//
@discardableResult
func quadraticRecur(n: Int) -> Int {
if n <= 0 {
return 0
}
// nums n, n-1, ..., 2, 1
let nums = Array(repeating: 0, count: n)
print("递归 n = \(n) 中的 nums 长度 = \(nums.count)")
return quadraticRecur(n: n - 1)
}
//
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
}
@main
enum SpaceComplexity {
// Driver Code
static func main() {
let n = 5
//
constant(n: n)
// 线
linear(n: n)
linearRecur(n: n)
//
quadratic(n: n)
quadraticRecur(n: n)
//
let root = buildTree(n: n)
PrintUtil.printTree(root: root)
}
}

@ -131,40 +131,41 @@ func factorialRecur(n: Int) -> Int {
return count
}
func main() {
// n
let n = 8
print("输入数据大小 n =", n)
var count = constant(n: n)
print("常数阶的计算操作数量 =", count)
count = linear(n: n)
print("线性阶的计算操作数量 =", count)
count = arrayTraversal(nums: Array(repeating: 0, count: n))
print("线性阶(遍历数组)的计算操作数量 =", count)
count = quadratic(n: n)
print("平方阶的计算操作数量 =", count)
var nums = Array(sequence(first: n, next: { $0 > 0 ? $0 - 1 : nil })) // [n,n-1,...,2,1]
count = bubbleSort(nums: &nums)
print("平方阶(冒泡排序)的计算操作数量 =", count)
count = exponential(n: n)
print("指数阶(循环实现)的计算操作数量 =", count)
count = expRecur(n: n)
print("指数阶(递归实现)的计算操作数量 =", count)
count = logarithmic(n: n)
print("对数阶(循环实现)的计算操作数量 =", count)
count = logRecur(n: n)
print("对数阶(递归实现)的计算操作数量 =", count)
count = linearLogRecur(n: Double(n))
print("线性对数阶(递归实现)的计算操作数量 =", count)
count = factorialRecur(n: n)
print("阶乘阶(递归实现)的计算操作数量 =", count)
@main
enum TimeComplexity {
static func main() {
// n
let n = 8
print("输入数据大小 n =", n)
var count = constant(n: n)
print("常数阶的计算操作数量 =", count)
count = linear(n: n)
print("线性阶的计算操作数量 =", count)
count = arrayTraversal(nums: Array(repeating: 0, count: n))
print("线性阶(遍历数组)的计算操作数量 =", count)
count = quadratic(n: n)
print("平方阶的计算操作数量 =", count)
var nums = Array(sequence(first: n, next: { $0 > 0 ? $0 - 1 : nil })) // [n,n-1,...,2,1]
count = bubbleSort(nums: &nums)
print("平方阶(冒泡排序)的计算操作数量 =", count)
count = exponential(n: n)
print("指数阶(循环实现)的计算操作数量 =", count)
count = expRecur(n: n)
print("指数阶(递归实现)的计算操作数量 =", count)
count = logarithmic(n: n)
print("对数阶(循环实现)的计算操作数量 =", count)
count = logRecur(n: n)
print("对数阶(递归实现)的计算操作数量 =", count)
count = linearLogRecur(n: Double(n))
print("线性对数阶(递归实现)的计算操作数量 =", count)
count = factorialRecur(n: n)
print("阶乘阶(递归实现)的计算操作数量 =", count)
}
}
main()

@ -23,15 +23,16 @@ func findOne(nums: [Int]) -> Int {
return -1
}
// Driver Code
func main() {
for _ in 0 ..< 10 {
let n = 100
let nums = randomNumbers(n: n)
let index = findOne(nums: nums)
print("数组 [ 1, 2, ..., n ] 被打乱后 =", nums)
print("数字 1 的索引为", index)
@main
enum WorstBestTimeComplexity {
// Driver Code
static func main() {
for _ in 0 ..< 10 {
let n = 100
let nums = randomNumbers(n: n)
let index = findOne(nums: nums)
print("数组 [ 1, 2, ..., n ] 被打乱后 =", nums)
print("数字 1 的索引为", index)
}
}
}
main()

@ -0,0 +1,14 @@
/*
* File: ListNode.swift
* Created Time: 2023-01-02
* Author: nuomi1 (nuomi1@qq.com)
*/
public class ListNode {
public var val: Int //
public var next: ListNode? //
public init(x: Int) {
val = x
}
}

@ -0,0 +1,61 @@
/*
* File: PrintUtil.swift
* Created Time: 2023-01-02
* Author: nuomi1 (nuomi1@qq.com)
*/
public enum PrintUtil {
private class Trunk {
var prev: Trunk?
var str: String
init(prev: Trunk?, str: String) {
self.prev = prev
self.str = str
}
}
public static func printTree(root: TreeNode?) {
printTree(root: root, prev: nil, isLeft: false)
}
private static func printTree(root: TreeNode?, prev: Trunk?, isLeft: Bool) {
if root == nil {
return
}
var prevStr = " "
let trunk = Trunk(prev: prev, str: prevStr)
printTree(root: root?.right, prev: trunk, isLeft: true)
if prev == nil {
trunk.str = "———"
} else if isLeft {
trunk.str = "/———"
prevStr = " |"
} else {
trunk.str = "\\———"
prev?.str = prevStr
}
showTrunks(p: trunk)
print(" \(root!.val)")
if prev != nil {
prev?.str = prevStr
}
trunk.str = " |"
printTree(root: root?.left, prev: trunk, isLeft: false)
}
private static func showTrunks(p: Trunk?) {
if p == nil {
return
}
showTrunks(p: p?.prev)
print(p!.str, terminator: "")
}
}

@ -0,0 +1,17 @@
/*
* File: TreeNode.swift
* Created Time: 2023-01-02
* Author: nuomi1 (nuomi1@qq.com)
*/
public class TreeNode {
public var val: Int //
public var height: Int //
public var left: TreeNode? //
public var right: TreeNode? //
public init(x: Int) {
val = x
height = 0
}
}

@ -174,6 +174,34 @@ comments: true
}
```
=== "Swift"
```swift title=""
// 类
class Node {
var val: Int
var next: Node?
init(x: Int) {
val = x
}
}
// 函数
func function() -> Int {
// do something...
return 0
}
func algorithm(n: Int) -> Int { // 输入数据
let a = 0 // 暂存数据(常量)
var b = 0 // 暂存数据(变量)
let node = Node(x: 0) // 暂存数据(对象)
let c = function() // 栈帧空间(调用函数)
return a + b + c // 输出数据
}
```
## 推算方法
空间复杂度的推算方法和时间复杂度总体类似,只是从统计“计算操作数量”变为统计“使用空间大小”。与时间复杂度不同的是,**我们一般只关注「最差空间复杂度」**。这是因为内存空间是一个硬性要求,我们必须保证在所有输入数据下都有足够的内存空间预留。
@ -261,6 +289,18 @@ comments: true
}
```
=== "Swift"
```swift title=""
func algorithm(n: Int) {
let a = 0 // O(1)
let b = Array(repeating: 0, count: 10000) // O(1)
if n > 10 {
let nums = Array(repeating: 0, count: n) // O(n)
}
}
```
**在递归函数中,需要注意统计栈帧空间。** 例如函数 `loop()`,在循环中调用了 $n$ 次 `function()` ,每轮中的 `function()` 都返回并释放了栈帧空间,因此空间复杂度仍为 $O(1)$ 。而递归函数 `recur()` 在运行中会同时存在 $n$ 个未返回的 `recur()` ,从而使用 $O(n)$ 的栈帧空间。
=== "Java"
@ -387,6 +427,31 @@ comments: true
}
```
=== "Swift"
```swift title=""
@discardableResult
func function() -> Int {
// do something
return 0
}
// 循环 O(1)
func loop(n: Int) {
for _ in 0 ..< n {
function()
}
}
// 递归 O(n)
func recur(n: Int) {
if n == 1 {
return
}
recur(n: n - 1)
}
```
## 常见类型
设输入数据大小为 $n$ ,常见的空间复杂度类型有(从低到高排列)
@ -536,6 +601,27 @@ $$
}
```
=== "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()
}
}
```
### 线性阶 $O(n)$
线性阶常见于元素数量与 $n$ 成正比的数组、链表、栈、队列等。
@ -654,6 +740,20 @@ $$
}
```
=== "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)") })
}
```
以下递归函数会同时存在 $n$ 个未返回的 `algorithm()` 函数,使用 $O(n)$ 大小的栈帧空间。
=== "Java"
@ -731,6 +831,19 @@ $$
}
```
=== "Swift"
```swift title="space_complexity.swift"
// 线性阶(递归实现)
func linearRecur(n: Int) {
print("递归 n = \(n)")
if n == 1 {
return
}
linearRecur(n: n - 1)
}
```
![space_complexity_recursive_linear](space_complexity.assets/space_complexity_recursive_linear.png)
<p align="center"> Fig. 递归函数产生的线性阶空间复杂度 </p>
@ -838,6 +951,16 @@ $$
```
=== "Swift"
```swift title="space_complexity.swift"
// 平方阶
func quadratic(n: Int) {
// 二维列表占用 O(n^2) 空间
let numList = Array(repeating: Array(repeating: 0, count: n), count: n)
}
```
在以下递归函数中,同时存在 $n$ 个未返回的 `algorithm()` ,并且每个函数中都初始化了一个数组,长度分别为 $n, n-1, n-2, ..., 2, 1$ ,平均长度为 $\frac{n}{2}$ ,因此总体使用 $O(n^2)$ 空间。
=== "Java"
@ -921,6 +1044,20 @@ $$
```
=== "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)
}
```
![space_complexity_recursive_quadratic](space_complexity.assets/space_complexity_recursive_quadratic.png)
<p align="center"> Fig. 递归函数产生的平方阶空间复杂度 </p>
@ -1014,6 +1151,21 @@ $$
}
```
=== "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
}
```
![space_complexity_exponential](space_complexity.assets/space_complexity_exponential.png)
<p align="center"> Fig. 满二叉树下的指数阶空间复杂度 </p>

Loading…
Cancel
Save