Merge pull request #218 from nuomi1/feature/linked_list-Swift

feat: add Swift codes for linked_list article
This commit is contained in:
Yudong Jin 2023-01-09 02:08:43 +08:00 committed by GitHub
commit 00e5dfa260
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 244 additions and 73 deletions

View file

@ -10,6 +10,7 @@ let package = Package(
.executable(name: "space_complexity", targets: ["space_complexity"]), .executable(name: "space_complexity", targets: ["space_complexity"]),
.executable(name: "leetcode_two_sum", targets: ["leetcode_two_sum"]), .executable(name: "leetcode_two_sum", targets: ["leetcode_two_sum"]),
.executable(name: "array", targets: ["array"]), .executable(name: "array", targets: ["array"]),
.executable(name: "linked_list", targets: ["linked_list"]),
], ],
targets: [ targets: [
.target(name: "utils", path: "utils"), .target(name: "utils", path: "utils"),
@ -18,5 +19,6 @@ let package = Package(
.executableTarget(name: "space_complexity", dependencies: ["utils"], path: "chapter_computational_complexity", sources: ["space_complexity.swift"]), .executableTarget(name: "space_complexity", dependencies: ["utils"], path: "chapter_computational_complexity", sources: ["space_complexity.swift"]),
.executableTarget(name: "leetcode_two_sum", path: "chapter_computational_complexity", sources: ["leetcode_two_sum.swift"]), .executableTarget(name: "leetcode_two_sum", path: "chapter_computational_complexity", sources: ["leetcode_two_sum.swift"]),
.executableTarget(name: "array", path: "chapter_array_and_linkedlist", sources: ["array.swift"]), .executableTarget(name: "array", path: "chapter_array_and_linkedlist", sources: ["array.swift"]),
.executableTarget(name: "linked_list", dependencies: ["utils"], path: "chapter_array_and_linkedlist", sources: ["linked_list.swift"]),
] ]
) )

View file

@ -0,0 +1,91 @@
/**
* File: linked_list.swift
* Created Time: 2023-01-08
* Author: nuomi1 (nuomi1@qq.com)
*/
import utils
/* n0 P */
func insert(n0: ListNode, P: ListNode) {
let n1 = n0.next
n0.next = P
P.next = n1
}
/* n0 */
func remove(n0: ListNode) {
if n0.next == nil {
return
}
// n0 -> P -> n1
let P = n0.next
let n1 = P?.next
n0.next = n1
P?.next = nil
}
/* 访 index */
func access(head: ListNode, index: Int) -> ListNode? {
var head: ListNode? = head
for _ in 0 ..< index {
head = head?.next
if head == nil {
return nil
}
}
return head
}
/* target */
func find(head: ListNode, target: Int) -> Int {
var head: ListNode? = head
var index = 0
while head != nil {
if head?.val == target {
return index
}
head = head?.next
index += 1
}
return -1
}
@main
enum LinkedList {
/* Driver Code */
static func main() {
/* */
//
let n0 = ListNode(x: 1)
let n1 = ListNode(x: 3)
let n2 = ListNode(x: 2)
let n3 = ListNode(x: 5)
let n4 = ListNode(x: 4)
//
n0.next = n1
n1.next = n2
n2.next = n3
n3.next = n4
print("初始化的链表为")
PrintUtil.printLinkedList(head: n0)
/* */
insert(n0: n0, P: ListNode(x: 0))
print("插入结点后的链表为")
PrintUtil.printLinkedList(head: n0)
/* */
remove(n0: n0)
print("删除结点后的链表为")
PrintUtil.printLinkedList(head: n0)
/* 访 */
let node = access(head: n0, index: 3)
print("链表中索引 3 处的结点的值 = \(node!.val)")
/* */
let index = find(head: n0, target: 2)
print("链表中值为 2 的结点的索引 = \(index)")
}
}

View file

@ -6,14 +6,14 @@
import utils import utils
// /* */
@discardableResult @discardableResult
func function() -> Int { func function() -> Int {
// do something // do something
return 0 return 0
} }
// /* */
func constant(n: Int) { func constant(n: Int) {
// O(1) // O(1)
let a = 0 let a = 0
@ -30,7 +30,7 @@ func constant(n: Int) {
} }
} }
// 线 /* 线 */
func linear(n: Int) { func linear(n: Int) {
// n O(n) // n O(n)
let nums = Array(repeating: 0, count: n) let nums = Array(repeating: 0, count: n)
@ -40,7 +40,7 @@ func linear(n: Int) {
let map = Dictionary(uniqueKeysWithValues: (0 ..< n).map { ($0, "\($0)") }) let map = Dictionary(uniqueKeysWithValues: (0 ..< n).map { ($0, "\($0)") })
} }
// 线 /* 线 */
func linearRecur(n: Int) { func linearRecur(n: Int) {
print("递归 n = \(n)") print("递归 n = \(n)")
if n == 1 { if n == 1 {
@ -49,13 +49,13 @@ func linearRecur(n: Int) {
linearRecur(n: n - 1) linearRecur(n: n - 1)
} }
// /* */
func quadratic(n: Int) { func quadratic(n: Int) {
// O(n^2) // O(n^2)
let numList = Array(repeating: Array(repeating: 0, count: n), count: n) let numList = Array(repeating: Array(repeating: 0, count: n), count: n)
} }
// /* */
@discardableResult @discardableResult
func quadraticRecur(n: Int) -> Int { func quadraticRecur(n: Int) -> Int {
if n <= 0 { if n <= 0 {
@ -67,7 +67,7 @@ func quadraticRecur(n: Int) -> Int {
return quadraticRecur(n: n - 1) return quadraticRecur(n: n - 1)
} }
// /* */
func buildTree(n: Int) -> TreeNode? { func buildTree(n: Int) -> TreeNode? {
if n == 0 { if n == 0 {
return nil return nil
@ -80,7 +80,7 @@ func buildTree(n: Int) -> TreeNode? {
@main @main
enum SpaceComplexity { enum SpaceComplexity {
// Driver Code /* Driver Code */
static func main() { static func main() {
let n = 5 let n = 5
// //

View file

@ -4,7 +4,7 @@
* Author: nuomi1 (nuomi1@qq.com) * Author: nuomi1 (nuomi1@qq.com)
*/ */
// /* */
func constant(n: Int) -> Int { func constant(n: Int) -> Int {
var count = 0 var count = 0
let size = 100_000 let size = 100_000
@ -14,7 +14,7 @@ func constant(n: Int) -> Int {
return count return count
} }
// 线 /* 线 */
func linear(n: Int) -> Int { func linear(n: Int) -> Int {
var count = 0 var count = 0
for _ in 0 ..< n { for _ in 0 ..< n {
@ -23,7 +23,7 @@ func linear(n: Int) -> Int {
return count return count
} }
// 线 /* 线 */
func arrayTraversal(nums: [Int]) -> Int { func arrayTraversal(nums: [Int]) -> Int {
var count = 0 var count = 0
// //
@ -33,7 +33,7 @@ func arrayTraversal(nums: [Int]) -> Int {
return count return count
} }
// /* */
func quadratic(n: Int) -> Int { func quadratic(n: Int) -> Int {
var count = 0 var count = 0
// //
@ -45,7 +45,7 @@ func quadratic(n: Int) -> Int {
return count return count
} }
// /* */
func bubbleSort(nums: inout [Int]) -> Int { func bubbleSort(nums: inout [Int]) -> Int {
var count = 0 // var count = 0 //
// n-1, n-2, ..., 1 // n-1, n-2, ..., 1
@ -64,7 +64,7 @@ func bubbleSort(nums: inout [Int]) -> Int {
return count return count
} }
// /* */
func exponential(n: Int) -> Int { func exponential(n: Int) -> Int {
var count = 0 var count = 0
var base = 1 var base = 1
@ -79,7 +79,7 @@ func exponential(n: Int) -> Int {
return count return count
} }
// /* */
func expRecur(n: Int) -> Int { func expRecur(n: Int) -> Int {
if n == 1 { if n == 1 {
return 1 return 1
@ -87,7 +87,7 @@ func expRecur(n: Int) -> Int {
return expRecur(n: n - 1) + expRecur(n: n - 1) + 1 return expRecur(n: n - 1) + expRecur(n: n - 1) + 1
} }
// /* */
func logarithmic(n: Int) -> Int { func logarithmic(n: Int) -> Int {
var count = 0 var count = 0
var n = n var n = n
@ -98,7 +98,7 @@ func logarithmic(n: Int) -> Int {
return count return count
} }
// /* */
func logRecur(n: Int) -> Int { func logRecur(n: Int) -> Int {
if n <= 1 { if n <= 1 {
return 0 return 0
@ -106,7 +106,7 @@ func logRecur(n: Int) -> Int {
return logRecur(n: n / 2) + 1 return logRecur(n: n / 2) + 1
} }
// 线 /* 线 */
func linearLogRecur(n: Double) -> Int { func linearLogRecur(n: Double) -> Int {
if n <= 1 { if n <= 1 {
return 1 return 1
@ -118,7 +118,7 @@ func linearLogRecur(n: Double) -> Int {
return count return count
} }
// /* */
func factorialRecur(n: Int) -> Int { func factorialRecur(n: Int) -> Int {
if n == 0 { if n == 0 {
return 1 return 1
@ -133,39 +133,40 @@ func factorialRecur(n: Int) -> Int {
@main @main
enum TimeComplexity { enum TimeComplexity {
/* Driver Code */
static func main() { static func main() {
// n // n
let n = 8 let n = 8
print("输入数据大小 n =", n) print("输入数据大小 n = \(n)")
var count = constant(n: n) var count = constant(n: n)
print("常数阶的计算操作数量 =", count) print("常数阶的计算操作数量 = \(count)")
count = linear(n: n) count = linear(n: n)
print("线性阶的计算操作数量 =", count) print("线性阶的计算操作数量 = \(count)")
count = arrayTraversal(nums: Array(repeating: 0, count: n)) count = arrayTraversal(nums: Array(repeating: 0, count: n))
print("线性阶(遍历数组)的计算操作数量 =", count) print("线性阶(遍历数组)的计算操作数量 = \(count)")
count = quadratic(n: n) count = quadratic(n: n)
print("平方阶的计算操作数量 =", count) print("平方阶的计算操作数量 = \(count)")
var nums = Array(sequence(first: n, next: { $0 > 0 ? $0 - 1 : nil })) // [n,n-1,...,2,1] var nums = Array(sequence(first: n, next: { $0 > 0 ? $0 - 1 : nil })) // [n,n-1,...,2,1]
count = bubbleSort(nums: &nums) count = bubbleSort(nums: &nums)
print("平方阶(冒泡排序)的计算操作数量 =", count) print("平方阶(冒泡排序)的计算操作数量 = \(count)")
count = exponential(n: n) count = exponential(n: n)
print("指数阶(循环实现)的计算操作数量 =", count) print("指数阶(循环实现)的计算操作数量 = \(count)")
count = expRecur(n: n) count = expRecur(n: n)
print("指数阶(递归实现)的计算操作数量 =", count) print("指数阶(递归实现)的计算操作数量 = \(count)")
count = logarithmic(n: n) count = logarithmic(n: n)
print("对数阶(循环实现)的计算操作数量 =", count) print("对数阶(循环实现)的计算操作数量 = \(count)")
count = logRecur(n: n) count = logRecur(n: n)
print("对数阶(递归实现)的计算操作数量 =", count) print("对数阶(递归实现)的计算操作数量 = \(count)")
count = linearLogRecur(n: Double(n)) count = linearLogRecur(n: Double(n))
print("线性对数阶(递归实现)的计算操作数量 =", count) print("线性对数阶(递归实现)的计算操作数量 = \(count)")
count = factorialRecur(n: n) count = factorialRecur(n: n)
print("阶乘阶(递归实现)的计算操作数量 =", count) print("阶乘阶(递归实现)的计算操作数量 = \(count)")
} }
} }

View file

@ -4,7 +4,7 @@
* Author: nuomi1 (nuomi1@qq.com) * Author: nuomi1 (nuomi1@qq.com)
*/ */
// { 1, 2, ..., n } /* { 1, 2, ..., n } */
func randomNumbers(n: Int) -> [Int] { func randomNumbers(n: Int) -> [Int] {
// nums = { 1, 2, 3, ..., n } // nums = { 1, 2, 3, ..., n }
var nums = Array(1 ... n) var nums = Array(1 ... n)
@ -13,7 +13,7 @@ func randomNumbers(n: Int) -> [Int] {
return nums return nums
} }
// nums 1 /* nums 1 */
func findOne(nums: [Int]) -> Int { func findOne(nums: [Int]) -> Int {
for i in nums.indices { for i in nums.indices {
if nums[i] == 1 { if nums[i] == 1 {
@ -25,14 +25,14 @@ func findOne(nums: [Int]) -> Int {
@main @main
enum WorstBestTimeComplexity { enum WorstBestTimeComplexity {
// Driver Code /* Driver Code */
static func main() { static func main() {
for _ in 0 ..< 10 { for _ in 0 ..< 10 {
let n = 100 let n = 100
let nums = randomNumbers(n: n) let nums = randomNumbers(n: n)
let index = findOne(nums: nums) let index = findOne(nums: nums)
print("数组 [ 1, 2, ..., n ] 被打乱后 =", nums) print("数组 [ 1, 2, ..., n ] 被打乱后 = \(nums)")
print("数字 1 的索引为", index) print("数字 1 的索引为 \(index)")
} }
} }
} }

View file

@ -15,6 +15,16 @@ public enum PrintUtil {
} }
} }
public static func printLinkedList(head: ListNode) {
var head: ListNode? = head
var list: [String] = []
while head != nil {
list.append("\(head!.val)")
head = head?.next
}
print(list.joined(separator: " -> "))
}
public static func printTree(root: TreeNode?) { public static func printTree(root: TreeNode?) {
printTree(root: root, prev: nil, isLeft: false) printTree(root: root, prev: nil, isLeft: false)
} }

View file

@ -84,7 +84,7 @@ comments: true
=== "Swift" === "Swift"
```swift title="array.swift" ```swift title="array.swift"
// 初始化数组 /* 初始化数组 */
let arr = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0] let arr = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0]
let nums = [1, 3, 2, 5, 4] let nums = [1, 3, 2, 5, 4]
``` ```
@ -204,7 +204,7 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
=== "Swift" === "Swift"
```swift title="array.swift" ```swift title="array.swift"
// 随机返回一个数组元素 /* 随机返回一个数组元素 */
func randomAccess(nums: [Int]) -> Int { func randomAccess(nums: [Int]) -> Int {
// 在区间 [0, nums.count) 中随机抽取一个数字 // 在区间 [0, nums.count) 中随机抽取一个数字
let randomIndex = nums.indices.randomElement()! let randomIndex = nums.indices.randomElement()!
@ -341,7 +341,7 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
=== "Swift" === "Swift"
```swift title="array.swift" ```swift title="array.swift"
// 扩展数组长度 /* 扩展数组长度 */
func extend(nums: [Int], enlarge: Int) -> [Int] { func extend(nums: [Int], enlarge: Int) -> [Int] {
// 初始化一个扩展长度后的数组 // 初始化一个扩展长度后的数组
var res = Array(repeating: 0, count: nums.count + enlarge) var res = Array(repeating: 0, count: nums.count + enlarge)
@ -526,7 +526,7 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
=== "Swift" === "Swift"
```swift title="array.swift" ```swift title="array.swift"
// 在数组的索引 index 处插入元素 num /* 在数组的索引 index 处插入元素 num */
func insert(nums: inout [Int], num: Int, index: Int) { func insert(nums: inout [Int], num: Int, index: Int) {
// 把索引 index 以及之后的所有元素向后移动一位 // 把索引 index 以及之后的所有元素向后移动一位
for i in sequence(first: nums.count - 1, next: { $0 > index + 1 ? $0 - 1 : nil }) { for i in sequence(first: nums.count - 1, next: { $0 > index + 1 ? $0 - 1 : nil }) {
@ -536,7 +536,7 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
nums[index] = num nums[index] = num
} }
// 删除索引 index 处元素 /* 删除索引 index 处元素 */
func remove(nums: inout [Int], index: Int) { func remove(nums: inout [Int], index: Int) {
let count = nums.count let count = nums.count
// 把索引 index 之后的所有元素向前移动一位 // 把索引 index 之后的所有元素向前移动一位
@ -674,7 +674,7 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
=== "Swift" === "Swift"
```swift title="array.swift" ```swift title="array.swift"
// 遍历数组 /* 遍历数组 */
func traverse(nums: [Int]) { func traverse(nums: [Int]) {
var count = 0 var count = 0
// 通过索引遍历数组 // 通过索引遍历数组
@ -793,7 +793,7 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
=== "Swift" === "Swift"
```swift title="array.swift" ```swift title="array.swift"
// 在数组中查找指定元素 /* 在数组中查找指定元素 */
func find(nums: [Int], target: Int) -> Int { func find(nums: [Int], target: Int) -> Int {
for i in nums.indices { for i in nums.indices {
if nums[i] == target { if nums[i] == target {

View file

@ -115,7 +115,15 @@ comments: true
=== "Swift" === "Swift"
```swift title="" ```swift title=""
/* 链表结点类 */
class ListNode {
var val: Int // 结点值
var next: ListNode? // 指向下一结点的指针(引用)
init(x: Int) { // 构造函数
val = x
}
}
``` ```
**尾结点指向什么?** 我们一般将链表的最后一个结点称为「尾结点」,其指向的是「空」,在 Java / C++ / Python 中分别记为 `null` / `nullptr` / `None` 。在不引起歧义下,本书都使用 `null` 来表示空。 **尾结点指向什么?** 我们一般将链表的最后一个结点称为「尾结点」,其指向的是「空」,在 Java / C++ / Python 中分别记为 `null` / `nullptr` / `None` 。在不引起歧义下,本书都使用 `null` 来表示空。
@ -255,7 +263,18 @@ comments: true
=== "Swift" === "Swift"
```swift title="linked_list.swift" ```swift title="linked_list.swift"
/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */
// 初始化各个结点
let n0 = ListNode(x: 1)
let n1 = ListNode(x: 3)
let n2 = ListNode(x: 2)
let n3 = ListNode(x: 5)
let n4 = ListNode(x: 4)
// 构建引用指向
n0.next = n1
n1.next = n2
n2.next = n3
n3.next = n4
``` ```
## 链表优点 ## 链表优点
@ -425,7 +444,24 @@ comments: true
=== "Swift" === "Swift"
```swift title="linked_list.swift" ```swift title="linked_list.swift"
/* 在链表的结点 n0 之后插入结点 P */
func insert(n0: ListNode, P: ListNode) {
let n1 = n0.next
n0.next = P
P.next = n1
}
/* 删除链表的结点 n0 之后的首个结点 */
func remove(n0: ListNode) {
if n0.next == nil {
return
}
// n0 -> P -> n1
let P = n0.next
let n1 = P?.next
n0.next = n1
P?.next = nil
}
``` ```
## 链表缺点 ## 链表缺点
@ -541,7 +577,17 @@ comments: true
=== "Swift" === "Swift"
```swift title="linked_list.swift" ```swift title="linked_list.swift"
/* 访问链表中索引为 index 的结点 */
func access(head: ListNode, index: Int) -> ListNode? {
var head: ListNode? = head
for _ in 0 ..< index {
head = head?.next
if head == nil {
return nil
}
}
return head
}
``` ```
**链表的内存占用多**。链表以结点为单位,每个结点除了保存值外,还需额外保存指针(引用)。这意味着同样数据量下,链表比数组需要占用更多内存空间。 **链表的内存占用多**。链表以结点为单位,每个结点除了保存值外,还需额外保存指针(引用)。这意味着同样数据量下,链表比数组需要占用更多内存空间。
@ -674,7 +720,19 @@ comments: true
=== "Swift" === "Swift"
```swift title="linked_list.swift" ```swift title="linked_list.swift"
/* 在链表中查找值为 target 的首个结点 */
func find(head: ListNode, target: Int) -> Int {
var head: ListNode? = head
var index = 0
while head != nil {
if head?.val == target {
return index
}
head = head?.next
index += 1
}
return -1
}
``` ```
## 常见链表类型 ## 常见链表类型
@ -793,7 +851,16 @@ comments: true
=== "Swift" === "Swift"
```swift title="" ```swift title=""
/* 双向链表结点类 */
class ListNode {
var val: Int // 结点值
var next: ListNode? // 指向后继结点的指针(引用)
var prev: ListNode? // 指向前驱结点的指针(引用)
init(x: Int) { // 构造函数
val = x
}
}
``` ```
![linkedlist_common_types](linked_list.assets/linkedlist_common_types.png) ![linkedlist_common_types](linked_list.assets/linkedlist_common_types.png)

View file

@ -177,7 +177,7 @@ comments: true
=== "Swift" === "Swift"
```swift title="" ```swift title=""
// 类 /* 类 */
class Node { class Node {
var val: Int var val: Int
var next: Node? var next: Node?
@ -187,7 +187,7 @@ comments: true
} }
} }
// 函数 /* 函数 */
func function() -> Int { func function() -> Int {
// do something... // do something...
return 0 return 0
@ -436,14 +436,14 @@ comments: true
return 0 return 0
} }
// 循环 O(1) /* 循环 O(1) */
func loop(n: Int) { func loop(n: Int) {
for _ in 0 ..< n { for _ in 0 ..< n {
function() function()
} }
} }
// 递归 O(n) /* 递归 O(n) */
func recur(n: Int) { func recur(n: Int) {
if n == 1 { if n == 1 {
return return
@ -604,7 +604,7 @@ $$
=== "Swift" === "Swift"
```swift title="space_complexity.swift" ```swift title="space_complexity.swift"
// 常数阶 /* 常数阶 */
func constant(n: Int) { func constant(n: Int) {
// 常量、变量、对象占用 O(1) 空间 // 常量、变量、对象占用 O(1) 空间
let a = 0 let a = 0
@ -743,7 +743,7 @@ $$
=== "Swift" === "Swift"
```swift title="space_complexity.swift" ```swift title="space_complexity.swift"
// 线性阶 /* 线性阶 */
func linear(n: Int) { func linear(n: Int) {
// 长度为 n 的数组占用 O(n) 空间 // 长度为 n 的数组占用 O(n) 空间
let nums = Array(repeating: 0, count: n) let nums = Array(repeating: 0, count: n)
@ -834,7 +834,7 @@ $$
=== "Swift" === "Swift"
```swift title="space_complexity.swift" ```swift title="space_complexity.swift"
// 线性阶(递归实现) /* 线性阶(递归实现) */
func linearRecur(n: Int) { func linearRecur(n: Int) {
print("递归 n = \(n)") print("递归 n = \(n)")
if n == 1 { if n == 1 {
@ -954,7 +954,7 @@ $$
=== "Swift" === "Swift"
```swift title="space_complexity.swift" ```swift title="space_complexity.swift"
// 平方阶 /* 平方阶 */
func quadratic(n: Int) { func quadratic(n: Int) {
// 二维列表占用 O(n^2) 空间 // 二维列表占用 O(n^2) 空间
let numList = Array(repeating: Array(repeating: 0, count: n), count: n) let numList = Array(repeating: Array(repeating: 0, count: n), count: n)
@ -1047,7 +1047,7 @@ $$
=== "Swift" === "Swift"
```swift title="space_complexity.swift" ```swift title="space_complexity.swift"
// 平方阶(递归实现) /* 平方阶(递归实现) */
func quadraticRecur(n: Int) -> Int { func quadraticRecur(n: Int) -> Int {
if n <= 0 { if n <= 0 {
return 0 return 0
@ -1154,7 +1154,7 @@ $$
=== "Swift" === "Swift"
```swift title="space_complexity.swift" ```swift title="space_complexity.swift"
// 指数阶(建立满二叉树) /* 指数阶(建立满二叉树) */
func buildTree(n: Int) -> TreeNode? { func buildTree(n: Int) -> TreeNode? {
if n == 0 { if n == 0 {
return nil return nil

View file

@ -876,7 +876,7 @@ $$
=== "Swift" === "Swift"
```swift title="time_complexity.swift" ```swift title="time_complexity.swift"
// 常数阶 /* 常数阶 */
func constant(n: Int) -> Int { func constant(n: Int) -> Int {
var count = 0 var count = 0
let size = 100000 let size = 100000
@ -990,7 +990,7 @@ $$
=== "Swift" === "Swift"
```swift title="time_complexity.swift" ```swift title="time_complexity.swift"
// 线性阶 /* 线性阶 */
func linear(n: Int) -> Int { func linear(n: Int) -> Int {
var count = 0 var count = 0
for _ in 0 ..< n { for _ in 0 ..< n {
@ -1121,7 +1121,7 @@ $$
=== "Swift" === "Swift"
```swift title="time_complexity.swift" ```swift title="time_complexity.swift"
// 线性阶(遍历数组) /* 线性阶(遍历数组) */
func arrayTraversal(nums: [Int]) -> Int { func arrayTraversal(nums: [Int]) -> Int {
var count = 0 var count = 0
// 循环次数与数组长度成正比 // 循环次数与数组长度成正比
@ -1267,7 +1267,7 @@ $$
=== "Swift" === "Swift"
```swift title="time_complexity.swift" ```swift title="time_complexity.swift"
// 平方阶 /* 平方阶 */
func quadratic(n: Int) -> Int { func quadratic(n: Int) -> Int {
var count = 0 var count = 0
// 循环次数与数组长度成平方关系 // 循环次数与数组长度成平方关系
@ -1477,7 +1477,7 @@ $$
=== "Swift" === "Swift"
```swift title="time_complexity.swift" ```swift title="time_complexity.swift"
// 平方阶(冒泡排序) /* 平方阶(冒泡排序) */
func bubbleSort(nums: inout [Int]) -> Int { func bubbleSort(nums: inout [Int]) -> Int {
var count = 0 // 计数器 var count = 0 // 计数器
// 外循环:待排序元素数量为 n-1, n-2, ..., 1 // 外循环:待排序元素数量为 n-1, n-2, ..., 1
@ -1656,7 +1656,7 @@ $$
=== "Swift" === "Swift"
```swift title="time_complexity.swift" ```swift title="time_complexity.swift"
// 指数阶(循环实现) /* 指数阶(循环实现) */
func exponential(n: Int) -> Int { func exponential(n: Int) -> Int {
var count = 0 var count = 0
var base = 1 var base = 1
@ -1764,7 +1764,7 @@ $$
=== "Swift" === "Swift"
```swift title="time_complexity.swift" ```swift title="time_complexity.swift"
// 指数阶(递归实现) /* 指数阶(递归实现) */
func expRecur(n: Int) -> Int { func expRecur(n: Int) -> Int {
if n == 1 { if n == 1 {
return 1 return 1
@ -1896,7 +1896,7 @@ $$
=== "Swift" === "Swift"
```swift title="time_complexity.swift" ```swift title="time_complexity.swift"
// 对数阶(循环实现) /* 对数阶(循环实现) */
func logarithmic(n: Int) -> Int { func logarithmic(n: Int) -> Int {
var count = 0 var count = 0
var n = n var n = n
@ -1999,7 +1999,7 @@ $$
=== "Swift" === "Swift"
```swift title="time_complexity.swift" ```swift title="time_complexity.swift"
// 对数阶(递归实现) /* 对数阶(递归实现) */
func logRecur(n: Int) -> Int { func logRecur(n: Int) -> Int {
if n <= 1 { if n <= 1 {
return 0 return 0
@ -2137,7 +2137,7 @@ $$
=== "Swift" === "Swift"
```swift title="time_complexity.swift" ```swift title="time_complexity.swift"
// 线性对数阶 /* 线性对数阶 */
func linearLogRecur(n: Double) -> Int { func linearLogRecur(n: Double) -> Int {
if n <= 1 { if n <= 1 {
return 1 return 1
@ -2288,7 +2288,7 @@ $$
=== "Swift" === "Swift"
```swift title="time_complexity.swift" ```swift title="time_complexity.swift"
// 阶乘阶(递归实现) /* 阶乘阶(递归实现) */
func factorialRecur(n: Int) -> Int { func factorialRecur(n: Int) -> Int {
if n == 0 { if n == 0 {
return 1 return 1
@ -2658,7 +2658,7 @@ $$
=== "Swift" === "Swift"
```swift title="worst_best_time_complexity.swift" ```swift title="worst_best_time_complexity.swift"
// 生成一个数组,元素为 { 1, 2, ..., n },顺序被打乱 /* 生成一个数组,元素为 { 1, 2, ..., n },顺序被打乱 */
func randomNumbers(n: Int) -> [Int] { func randomNumbers(n: Int) -> [Int] {
// 生成数组 nums = { 1, 2, 3, ..., n } // 生成数组 nums = { 1, 2, 3, ..., n }
var nums = Array(1 ... n) var nums = Array(1 ... n)
@ -2667,7 +2667,7 @@ $$
return nums return nums
} }
// 查找数组 nums 中数字 1 所在索引 /* 查找数组 nums 中数字 1 所在索引 */
func findOne(nums: [Int]) -> Int { func findOne(nums: [Int]) -> Int {
for i in nums.indices { for i in nums.indices {
if nums[i] == 1 { if nums[i] == 1 {
@ -2677,14 +2677,14 @@ $$
return -1 return -1
} }
// Driver Code /* Driver Code */
func main() { func main() {
for _ in 0 ..< 10 { for _ in 0 ..< 10 {
let n = 100 let n = 100
let nums = randomNumbers(n: n) let nums = randomNumbers(n: n)
let index = findOne(nums: nums) let index = findOne(nums: nums)
print("数组 [ 1, 2, ..., n ] 被打乱后 =", nums) print("数组 [ 1, 2, ..., n ] 被打乱后 = \(nums)")
print("数字 1 的索引为", index) print("数字 1 的索引为 \(index)")
} }
} }
``` ```

View file

@ -117,7 +117,7 @@ comments: true
=== "Swift" === "Swift"
```swift title="" ```swift title=""
// 使用多种「基本数据类型」来初始化「数组」 /* 使用多种「基本数据类型」来初始化「数组」 */
let numbers = Array(repeating: Int(), count: 5) let numbers = Array(repeating: Int(), count: 5)
let decimals = Array(repeating: Double(), count: 5) let decimals = Array(repeating: Double(), count: 5)
let characters = Array(repeating: Character("a"), count: 5) let characters = Array(repeating: Character("a"), count: 5)