Add build script for Swift.

This commit is contained in:
krahets
2023-02-08 20:30:05 +08:00
parent 05f0054005
commit 38751cc5f5
25 changed files with 128 additions and 1223 deletions

View File

@@ -137,25 +137,7 @@ $$
=== "Swift"
```swift title="binary_search.swift"
/* 二分查找(双闭区间) */
func binarySearch(nums: [Int], target: Int) -> Int {
// 初始化双闭区间 [0, n-1] ,即 i, j 分别指向数组首元素、尾元素
var i = 0
var j = nums.count - 1
// 循环,当搜索区间为空时跳出(当 i > j 时为空)
while i <= j {
let m = (i + j) / 2 // 计算中点索引 m
if nums[m] < target { // 此情况说明 target 在区间 [m+1, j] 中
i = m + 1
} else if nums[m] > target { // 此情况说明 target 在区间 [i, m-1] 中
j = m - 1
} else { // 找到目标元素,返回其索引
return m
}
}
// 未找到目标元素,返回 -1
return -1
}
[class]{}-[func]{binarySearch}
```
=== "Zig"
@@ -254,25 +236,7 @@ $$
=== "Swift"
```swift title="binary_search.swift"
/* 二分查找(左闭右开) */
func binarySearch1(nums: [Int], target: Int) -> Int {
// 初始化左闭右开 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
var i = 0
var j = nums.count
// 循环,当搜索区间为空时跳出(当 i = j 时为空)
while i < j {
let m = (i + j) / 2 // 计算中点索引 m
if nums[m] < target { // 此情况说明 target 在区间 [m+1, j) 中
i = m + 1
} else if nums[m] > target { // 此情况说明 target 在区间 [i, m) 中
j = m
} else { // 找到目标元素,返回其索引
return m
}
}
// 未找到目标元素,返回 -1
return -1
}
[class]{}-[func]{binarySearch1}
```
=== "Zig"

View File

@@ -82,12 +82,7 @@ comments: true
=== "Swift"
```swift title="hashing_search.swift"
/* 哈希查找(数组) */
func hashingSearchArray(map: [Int: Int], target: Int) -> Int {
// 哈希表的 key: 目标元素value: 索引
// 若哈希表中无此 key ,返回 -1
return map[target, default: -1]
}
[class]{}-[func]{hashingSearchArray}
```
=== "Zig"
@@ -167,12 +162,7 @@ comments: true
=== "Swift"
```swift title="hashing_search.swift"
/* 哈希查找(链表) */
func hashingSearchLinkedList(map: [Int: ListNode], target: Int) -> ListNode? {
// 哈希表的 key: 目标结点值value: 结点对象
// 若哈希表中无此 key ,返回 null
return map[target]
}
[class]{}-[func]{hashingSearchLinkedList}
```
=== "Zig"

View File

@@ -87,18 +87,7 @@ comments: true
=== "Swift"
```swift title="linear_search.swift"
/* 线性查找(数组) */
func linearSearchArray(nums: [Int], target: Int) -> Int {
// 遍历数组
for i in nums.indices {
// 找到目标元素,返回其索引
if nums[i] == target {
return i
}
}
// 未找到目标元素,返回 -1
return -1
}
[class]{}-[func]{linearSearchArray}
```
=== "Zig"
@@ -185,20 +174,7 @@ comments: true
=== "Swift"
```swift title="linear_search.swift"
/* 线性查找(链表) */
func linearSearchLinkedList(head: ListNode?, target: Int) -> ListNode? {
var head = head
// 遍历链表
while head != nil {
// 找到目标结点,返回之
if head?.val == target {
return head
}
head = head?.next
}
// 未找到目标结点,返回 null
return nil
}
[class]{}-[func]{linearSearchLinkedList}
```
=== "Zig"