feat: add Swift codes for chapter_searching articles (#309)

* feat: add Swift codes for linear_search article

* feat: add Swift codes for binary_search article

* feat: add Swift codes for hashing_search article
This commit is contained in:
nuomi1
2023-01-30 15:43:29 +08:00
committed by GitHub
parent 15c798046a
commit 1665fe176c
8 changed files with 261 additions and 7 deletions
+42 -3
View File
@@ -213,7 +213,25 @@ $$
=== "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
}
```
### “左闭右开”实现
@@ -383,7 +401,25 @@ $$
=== "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
}
```
### 两种表示对比
@@ -475,7 +511,10 @@ $$
=== "Swift"
```swift title=""
// (i + j) 有可能超出 int 的取值范围
let m = (i + j) / 2
// 更换为此写法则不会越界
let m = i + (j - 1) / 2
```
## 复杂度分析