This commit is contained in:
krahets
2023-05-21 19:29:43 +08:00
parent 0c64fc7315
commit 5a68f683b9
26 changed files with 93 additions and 93 deletions
+544
View File
@@ -0,0 +1,544 @@
---
comments: true
---
# 10.1.   二分查找
「二分查找 Binary Search」是一种基于分治思想的高效搜索算法。它利用数据的有序性,每轮减少一半搜索范围,直至找到目标元素或搜索区间为空为止。
我们先来求解一个简单的二分查找问题。
!!! question "给定一个长度为 $n$ 的有序数组 `nums` ,元素按从小到大的顺序排列。查找并返回元素 `target` 在该数组中的索引。若数组中不包含该元素,则返回 $-1$ 。数组中不包含重复元素。"
该数组的索引范围可以使用区间 $[0, n - 1]$ 来表示。其中,**中括号表示“闭区间”,即包含边界值本身**。在该表示下,区间 $[i, j]$ 在 $i = j$ 时仍包含一个元素,在 $i > j$ 时为空区间。
接下来,我们基于上述区间定义实现二分查找。先初始化指针 $i = 0$ 和 $j = n - 1$ ,分别指向数组首元素和尾元素。之后循环执行以下两个步骤:
1. 计算中点索引 $m = \lfloor {(i + j) / 2} \rfloor$ ,其中 $\lfloor \space \rfloor$ 表示向下取整操作。
2. 根据 `nums[m]``target` 缩小搜索区间,分为三种情况:
1.`nums[m] < target` 时,说明 `target` 在区间 $[m + 1, j]$ 中,因此执行 $i = m + 1$
2.`nums[m] > target` 时,说明 `target` 在区间 $[i, m - 1]$ 中,因此执行 $j = m - 1$
3.`nums[m] = target` 时,说明找到目标元素,直接返回索引 $m$ 即可;
**若数组不包含目标元素,搜索区间最终会缩小为空**,即达到 $i > j$ 。此时,终止循环并返回 $-1$ 即可。
如下图所示,为了更清晰地表示区间,我们以折线图的形式表示数组。
=== "<0>"
![二分查找步骤](binary_search.assets/binary_search_step0.png)
=== "<1>"
![binary_search_step1](binary_search.assets/binary_search_step1.png)
=== "<2>"
![binary_search_step2](binary_search.assets/binary_search_step2.png)
=== "<3>"
![binary_search_step3](binary_search.assets/binary_search_step3.png)
=== "<4>"
![binary_search_step4](binary_search.assets/binary_search_step4.png)
=== "<5>"
![binary_search_step5](binary_search.assets/binary_search_step5.png)
=== "<6>"
![binary_search_step6](binary_search.assets/binary_search_step6.png)
=== "<7>"
![binary_search_step7](binary_search.assets/binary_search_step7.png)
值得注意的是,**当数组长度 $n$ 很大时,加法 $i + j$ 的结果可能会超出 `int` 类型的取值范围**。为了避免大数越界,我们通常采用公式 $m = \lfloor {i + (j - i) / 2} \rfloor$ 来计算中点。
=== "Java"
```java title="binary_search.java"
/* 二分查找(双闭区间) */
int binarySearch(int[] nums, int target) {
// 初始化双闭区间 [0, n-1] ,即 i, j 分别指向数组首元素、尾元素
int i = 0, j = nums.length - 1;
// 循环,当搜索区间为空时跳出(当 i > j 时为空)
while (i <= j) {
int m = i + (j - i) / 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;
}
```
=== "C++"
```cpp title="binary_search.cpp"
/* 二分查找(双闭区间) */
int binarySearch(vector<int> &nums, int target) {
// 初始化双闭区间 [0, n-1] ,即 i, j 分别指向数组首元素、尾元素
int i = 0, j = nums.size() - 1;
// 循环,当搜索区间为空时跳出(当 i > j 时为空)
while (i <= j) {
int m = i + (j - i) / 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;
}
```
=== "Python"
```python title="binary_search.py"
def binary_search(nums: list[int], target: int) -> int:
"""二分查找(双闭区间)"""
# 初始化双闭区间 [0, n-1] ,即 i, j 分别指向数组首元素、尾元素
i, j = 0, len(nums) - 1
# 循环,当搜索区间为空时跳出(当 i > j 时为空)
while i <= j:
# 理论上 Python 的数字可以无限大(取决于内存大小),无需考虑大数越界问题
m = (i + j) // 2 # 计算中点索引 m
if nums[m] < target:
i = m + 1 # 此情况说明 target 在区间 [m+1, j] 中
elif nums[m] > target:
j = m - 1 # 此情况说明 target 在区间 [i, m-1] 中
else:
return m # 找到目标元素,返回其索引
return -1 # 未找到目标元素,返回 -1
```
=== "Go"
```go title="binary_search.go"
/* 二分查找(双闭区间) */
func binarySearch(nums []int, target int) int {
// 初始化双闭区间 [0, n-1] ,即 i, j 分别指向数组首元素、尾元素
i, j := 0, len(nums)-1
// 循环,当搜索区间为空时跳出(当 i > j 时为空)
for i <= j {
m := i + (j-i)/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
}
```
=== "JavaScript"
```javascript title="binary_search.js"
/* 二分查找(双闭区间) */
function binarySearch(nums, target) {
// 初始化双闭区间 [0, n-1] ,即 i, j 分别指向数组首元素、尾元素
let i = 0,
j = nums.length - 1;
// 循环,当搜索区间为空时跳出(当 i > j 时为空)
while (i <= j) {
// 计算中点索引 m ,使用 parseInt() 向下取整
const m = parseInt(i + (j - i) / 2);
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;
}
```
=== "TypeScript"
```typescript title="binary_search.ts"
/* 二分查找(双闭区间) */
function binarySearch(nums: number[], target: number): number {
// 初始化双闭区间 [0, n-1] ,即 i, j 分别指向数组首元素、尾元素
let i = 0,
j = nums.length - 1;
// 循环,当搜索区间为空时跳出(当 i > j 时为空)
while (i <= j) {
// 计算中点索引 m
const m = Math.floor(i + (j - i) / 2);
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;
}
}
return -1; // 未找到目标元素,返回 -1
}
```
=== "C"
```c title="binary_search.c"
/* 二分查找(双闭区间) */
int binarySearch(int *nums, int len, int target) {
// 初始化双闭区间 [0, n-1] ,即 i, j 分别指向数组首元素、尾元素
int i = 0, j = len - 1;
// 循环,当搜索区间为空时跳出(当 i > j 时为空)
while (i <= j) {
int m = i + (j - i) / 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;
}
```
=== "C#"
```csharp title="binary_search.cs"
/* 二分查找(双闭区间) */
int binarySearch(int[] nums, int target) {
// 初始化双闭区间 [0, n-1] ,即 i, j 分别指向数组首元素、尾元素
int i = 0, j = nums.Length - 1;
// 循环,当搜索区间为空时跳出(当 i > j 时为空)
while (i <= j) {
int m = i + (j - i) / 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;
}
```
=== "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 - i) / 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
}
```
=== "Zig"
```zig title="binary_search.zig"
// 二分查找(双闭区间)
fn binarySearch(comptime T: type, nums: std.ArrayList(T), target: T) T {
// 初始化双闭区间 [0, n-1] ,即 i, j 分别指向数组首元素、尾元素
var i: usize = 0;
var j: usize = nums.items.len - 1;
// 循环,当搜索区间为空时跳出(当 i > j 时为空)
while (i <= j) {
var m = i + (j - i) / 2; // 计算中点索引 m
if (nums.items[m] < target) { // 此情况说明 target 在区间 [m+1, j] 中
i = m + 1;
} else if (nums.items[m] > target) { // 此情况说明 target 在区间 [i, m-1] 中
j = m - 1;
} else { // 找到目标元素,返回其索引
return @intCast(T, m);
}
}
// 未找到目标元素,返回 -1
return -1;
}
```
时间复杂度为 $O(\log n)$ 。每轮缩小一半区间,因此二分循环次数为 $\log_2 n$ 。
空间复杂度为 $O(1)$ 。指针 `i` , `j` 使用常数大小空间。
## 10.1.1. &nbsp; 区间表示方法
除了上述的双闭区间外,常见的区间表示还有“左闭右开”区间,定义为 $[0, n)$ ,即左边界包含自身,右边界不包含自身。在该表示下,区间 $[i, j]$ 在 $i = j$ 时为空。
我们可以基于该表示实现具有相同功能的二分查找算法。
=== "Java"
```java title="binary_search.java"
/* 二分查找(左闭右开) */
int binarySearchLCRO(int[] nums, int target) {
// 初始化左闭右开 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
int i = 0, j = nums.length;
// 循环,当搜索区间为空时跳出(当 i = j 时为空)
while (i < j) {
int m = i + (j - i) / 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;
}
```
=== "C++"
```cpp title="binary_search.cpp"
/* 二分查找(左闭右开) */
int binarySearchLCRO(vector<int> &nums, int target) {
// 初始化左闭右开 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
int i = 0, j = nums.size();
// 循环,当搜索区间为空时跳出(当 i = j 时为空)
while (i < j) {
int m = i + (j - i) / 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;
}
```
=== "Python"
```python title="binary_search.py"
def binary_search_lcro(nums: list[int], target: int) -> int:
"""二分查找(左闭右开)"""
# 初始化左闭右开 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
i, j = 0, len(nums)
# 循环,当搜索区间为空时跳出(当 i = j 时为空)
while i < j:
m = (i + j) // 2 # 计算中点索引 m
if nums[m] < target:
i = m + 1 # 此情况说明 target 在区间 [m+1, j) 中
elif nums[m] > target:
j = m # 此情况说明 target 在区间 [i, m) 中
else:
return m # 找到目标元素,返回其索引
return -1 # 未找到目标元素,返回 -1
```
=== "Go"
```go title="binary_search.go"
/* 二分查找(左闭右开) */
func binarySearchLCRO(nums []int, target int) int {
// 初始化左闭右开 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
i, j := 0, len(nums)
// 循环,当搜索区间为空时跳出(当 i = j 时为空)
for i < j {
m := i + (j-i)/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
}
```
=== "JavaScript"
```javascript title="binary_search.js"
/* 二分查找(左闭右开) */
function binarySearchLCRO(nums, target) {
// 初始化左闭右开 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
let i = 0,
j = nums.length;
// 循环,当搜索区间为空时跳出(当 i = j 时为空)
while (i < j) {
// 计算中点索引 m ,使用 parseInt() 向下取整
const m = parseInt(i + (j - i) / 2);
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;
}
```
=== "TypeScript"
```typescript title="binary_search.ts"
/* 二分查找(左闭右开) */
function binarySearchLCRO(nums: number[], target: number): number {
// 初始化左闭右开 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
let i = 0,
j = nums.length;
// 循环,当搜索区间为空时跳出(当 i = j 时为空)
while (i < j) {
// 计算中点索引 m
const m = Math.floor(i + (j - i) / 2);
if (nums[m] < target) {
// 此情况说明 target 在区间 [m+1, j) 中
i = m + 1;
} else if (nums[m] > target) {
// 此情况说明 target 在区间 [i, m) 中
j = m;
} else {
// 找到目标元素,返回其索引
return m;
}
}
return -1; // 未找到目标元素,返回 -1
}
```
=== "C"
```c title="binary_search.c"
/* 二分查找(左闭右开) */
int binarySearchLCRO(int *nums, int len, int target) {
// 初始化左闭右开 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
int i = 0, j = len;
// 循环,当搜索区间为空时跳出(当 i = j 时为空)
while (i < j) {
int m = i + (j - i) / 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;
}
```
=== "C#"
```csharp title="binary_search.cs"
/* 二分查找(左闭右开) */
int binarySearchLCRO(int[] nums, int target) {
// 初始化左闭右开 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
int i = 0, j = nums.Length;
// 循环,当搜索区间为空时跳出(当 i = j 时为空)
while (i < j) {
int m = i + (j - i) / 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;
}
```
=== "Swift"
```swift title="binary_search.swift"
/* 二分查找(左闭右开) */
func binarySearchLCRO(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 - i) / 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
}
```
=== "Zig"
```zig title="binary_search.zig"
// 二分查找(左闭右开)
fn binarySearchLCRO(comptime T: type, nums: std.ArrayList(T), target: T) T {
// 初始化左闭右开 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
var i: usize = 0;
var j: usize = nums.items.len;
// 循环,当搜索区间为空时跳出(当 i = j 时为空)
while (i <= j) {
var m = i + (j - i) / 2; // 计算中点索引 m
if (nums.items[m] < target) { // 此情况说明 target 在区间 [m+1, j) 中
i = m + 1;
} else if (nums.items[m] > target) { // 此情况说明 target 在区间 [i, m) 中
j = m;
} else { // 找到目标元素,返回其索引
return @intCast(T, m);
}
}
// 未找到目标元素,返回 -1
return -1;
}
```
如下图所示,在两种区间表示下,二分查找算法的初始化、循环条件和缩小区间操作皆有所不同。
在“双闭区间”表示法中,由于左右边界都被定义为闭区间,因此指针 $i$ 和 $j$ 缩小区间操作也是对称的。这样更不容易出错。因此,**我们通常采用“双闭区间”的写法**。
![两种区间定义](binary_search.assets/binary_search_ranges.png)
<p align="center"> Fig. 两种区间定义 </p>
## 10.1.2. &nbsp; 优点与局限性
二分查找在时间和空间方面都有较好的性能:
- **二分查找的时间效率高**。在大数据量下,对数阶的时间复杂度具有显著优势。例如,当数据大小 $n = 2^{20}$ 时,线性查找需要 $2^{20} = 1048576$ 轮循环,而二分查找仅需 $\log_2 2^{20} = 20$ 轮循环。
- **二分查找无需额外空间**。相较于需要借助额外空间的搜索算法(例如哈希查找),二分查找更加节省空间。
然而,二分查找并非适用于所有情况,原因如下:
- **二分查找仅适用于有序数据**。若输入数据无序,为了使用二分查找而专门进行排序,得不偿失。因为排序算法的时间复杂度通常为 $O(n \log n)$ ,比线性查找和二分查找都更高。对于频繁插入元素的场景,为保持数组有序性,需要将元素插入到特定位置,时间复杂度为 $O(n)$ ,也是非常昂贵的。
- **二分查找仅适用于数组**。二分查找需要跳跃式(非连续地)访问元素,而在链表中执行跳跃式访问的效率较低,因此不适合应用在链表或基于链表实现的数据结构。
- **小数据量下,线性查找性能更佳**。在线性查找中,每轮只需要 1 次判断操作;而在二分查找中,需要 1 次加法、1 次除法、1 ~ 3 次判断操作、1 次加法(减法),共 4 ~ 6 个单元操作;因此,当数据量 $n$ 较小时,线性查找反而比二分查找更快。
+278
View File
@@ -0,0 +1,278 @@
---
comments: true
---
# 10.2. &nbsp; 二分查找边界
上一节规定目标元素在数组中是唯一的。如果目标元素在数组中多次出现,上节介绍的方法只能保证返回其中一个目标元素的索引,**而无法确定该索引的左边和右边还有多少目标元素**。
为了查找最左一个 `target` ,我们可以先进行二分查找,找到任意一个目标元素,**再加一个向左遍历的线性查找**,找到最左的 `target` 返回即可。然而,由于加入了线性查找,这个方法的时间复杂度可能会劣化至 $O(n)$ 。
![线性查找最左元素](binary_search_edge.assets/binary_search_left_edge_naive.png)
<p align="center"> Fig. 线性查找最左元素 </p>
## 10.2.1. &nbsp; 查找最左一个元素
!!! question "查找并返回元素 `target` 在有序数组 `nums` 中首次出现的索引。若数组中不包含该元素,则返回 $-1$ 。数组可能包含重复元素。"
实际上,我们可以仅通过二分查找解决以上问题。方法的整体框架不变,先计算中点索引 `m` ,再判断 `target``nums[m]` 大小关系:
-`nums[m] < target``nums[m] > target` 时,说明还没有找到 `target` ,因此采取与上节代码相同的缩小区间操作。
-`nums[m] == target` 时,说明找到了一个目标元素,此时应该如何缩小区间?
对于该情况,**我们可以将查找目标想象为 `leftarget`**,其中 `leftarget` 表示从右到左首个小于 `target` 的元素。具体来说:
-`nums[m] == target` 时,说明 `leftarget` 在区间 `[i, m - 1]` 中,因此采用 `j = m - 1` 来缩小区间,**从而使指针 `j``leftarget` 收缩靠近**。
- 二分查找完成后,`i` 指向最左一个 `target` `j` 指向 `leftarget` ,因此最终返回索引 `i` 即可。
=== "<1>"
![二分查找最左元素的步骤](binary_search_edge.assets/binary_search_left_edge_step1.png)
=== "<2>"
![binary_search_left_edge_step2](binary_search_edge.assets/binary_search_left_edge_step2.png)
=== "<3>"
![binary_search_left_edge_step3](binary_search_edge.assets/binary_search_left_edge_step3.png)
=== "<4>"
![binary_search_left_edge_step4](binary_search_edge.assets/binary_search_left_edge_step4.png)
=== "<5>"
![binary_search_left_edge_step5](binary_search_edge.assets/binary_search_left_edge_step5.png)
=== "<6>"
![binary_search_left_edge_step6](binary_search_edge.assets/binary_search_left_edge_step6.png)
=== "<7>"
![binary_search_left_edge_step7](binary_search_edge.assets/binary_search_left_edge_step7.png)
=== "<8>"
![binary_search_left_edge_step8](binary_search_edge.assets/binary_search_left_edge_step8.png)
注意,数组可能不包含目标元素 `target` 。因此在函数返回前,我们需要先判断 `nums[i]``target` 是否相等。另外,当 `target` 大于数组中的所有元素时,索引 `i` 会越界,因此也需要额外判断。
=== "Java"
```java title="binary_search_edge.java"
/* 二分查找最左一个元素 */
int binarySearchLeftEdge(int[] nums, int target) {
int i = 0, j = nums.length - 1; // 初始化双闭区间 [0, n-1]
while (i <= j) {
int m = i + (j - i) / 2; // 计算中点索引 m
if (nums[m] < target)
i = m + 1; // target 在区间 [m+1, j] 中
else if (nums[m] > target)
j = m - 1; // target 在区间 [i, m-1] 中
else
j = m - 1; // 首个小于 target 的元素在区间 [i, m-1] 中
}
if (i == nums.length || nums[i] != target)
return -1; // 未找到目标元素,返回 -1
return i;
}
```
=== "C++"
```cpp title="binary_search_edge.cpp"
/* 二分查找最左一个元素 */
int binarySearchLeftEdge(vector<int> &nums, int target) {
int i = 0, j = nums.size() - 1; // 初始化双闭区间 [0, n-1]
while (i <= j) {
int m = i + (j - i) / 2; // 计算中点索引 m
if (nums[m] < target)
i = m + 1; // target 在区间 [m+1, j] 中
else if (nums[m] > target)
j = m - 1; // target 在区间 [i, m-1] 中
else
j = m - 1; // 首个小于 target 的元素在区间 [i, m-1] 中
}
if (i == nums.size() || nums[i] != target)
return -1; // 未找到目标元素,返回 -1
return i;
}
```
=== "Python"
```python title="binary_search_edge.py"
def binary_search_left_edge(nums: list[int], target: int) -> int:
"""二分查找最左一个元素"""
# 初始化双闭区间 [0, n-1] ,即 i, j 分别指向数组首元素、尾元素
i, j = 0, len(nums) - 1
while i <= j:
m = (i + j) // 2 # 计算中点索引 m
if nums[m] < target:
i = m + 1 # 此情况说明 target 在区间 [m+1, j] 中
elif nums[m] > target:
j = m - 1 # 此情况说明 target 在区间 [i, m-1] 中
else:
j = m - 1 # 此情况说明首个小于 target 的元素在区间 [i, m-1] 中
if i == len(nums) or nums[i] != target:
return -1 # 未找到目标元素,返回 -1
return i
```
=== "Go"
```go title="binary_search_edge.go"
[class]{}-[func]{binarySearchLeftEdge}
```
=== "JavaScript"
```javascript title="binary_search_edge.js"
[class]{}-[func]{binarySearchLeftEdge}
```
=== "TypeScript"
```typescript title="binary_search_edge.ts"
[class]{}-[func]{binarySearchLeftEdge}
```
=== "C"
```c title="binary_search_edge.c"
[class]{}-[func]{binarySearchLeftEdge}
```
=== "C#"
```csharp title="binary_search_edge.cs"
[class]{binary_search_edge}-[func]{binarySearchLeftEdge}
```
=== "Swift"
```swift title="binary_search_edge.swift"
[class]{}-[func]{binarySearchLeftEdge}
```
=== "Zig"
```zig title="binary_search_edge.zig"
[class]{}-[func]{binarySearchLeftEdge}
```
## 10.2.2. &nbsp; 查找最右一个元素
类似地,我们也可以二分查找最右一个元素。设首个大于 `target` 的元素为 `rightarget` 。
- 当 `nums[m] == target` 时,说明 `rightarget` 在区间 `[m + 1, j]` 中,因此执行 `i = m + 1` 将搜索区间向右收缩。
- 完成二分后,`i` 指向 `rightarget` `j` 指向最右一个 `target` ,因此最终返回索引 `j` 即可。
=== "Java"
```java title="binary_search_edge.java"
/* 二分查找最右一个元素 */
int binarySearchRightEdge(int[] nums, int target) {
int i = 0, j = nums.length - 1; // 初始化双闭区间 [0, n-1]
while (i <= j) {
int m = i + (j - i) / 2; // 计算中点索引 m
if (nums[m] < target)
i = m + 1; // target 在区间 [m+1, j] 中
else if (nums[m] > target)
j = m - 1; // target 在区间 [i, m-1] 中
else
i = m + 1; // 首个大于 target 的元素在区间 [m+1, j] 中
}
if (j < 0 || nums[j] != target)
return -1; // 未找到目标元素,返回 -1
return j;
}
```
=== "C++"
```cpp title="binary_search_edge.cpp"
/* 二分查找最右一个元素 */
int binarySearchRightEdge(vector<int> &nums, int target) {
int i = 0, j = nums.size() - 1; // 初始化双闭区间 [0, n-1]
while (i <= j) {
int m = i + (j - i) / 2; // 计算中点索引 m
if (nums[m] < target)
i = m + 1; // target 在区间 [m+1, j] 中
else if (nums[m] > target)
j = m - 1; // target 在区间 [i, m-1] 中
else
i = m + 1; // 首个大于 target 的元素在区间 [m+1, j] 中
}
if (j < 0 || nums[j] != target)
return -1; // 未找到目标元素,返回 -1
return j;
}
```
=== "Python"
```python title="binary_search_edge.py"
def binary_search_right_edge(nums: list[int], target: int) -> int:
"""二分查找最右一个元素"""
# 初始化双闭区间 [0, n-1] ,即 i, j 分别指向数组首元素、尾元素
i, j = 0, len(nums) - 1
while i <= j:
m = (i + j) // 2 # 计算中点索引 m
if nums[m] < target:
i = m + 1 # target 在区间 [m+1, j] 中
elif nums[m] > target:
j = m - 1 # target 在区间 [i, m-1] 中
else:
i = m + 1 # 首个大于 target 的元素在区间 [m+1, j] 中
if j == len(nums) or nums[j] != target:
return -1 # 未找到目标元素,返回 -1
return j
```
=== "Go"
```go title="binary_search_edge.go"
[class]{}-[func]{binarySearchRightEdge}
```
=== "JavaScript"
```javascript title="binary_search_edge.js"
[class]{}-[func]{binarySearchRightEdge}
```
=== "TypeScript"
```typescript title="binary_search_edge.ts"
[class]{}-[func]{binarySearchRightEdge}
```
=== "C"
```c title="binary_search_edge.c"
[class]{}-[func]{binarySearchRightEdge}
```
=== "C#"
```csharp title="binary_search_edge.cs"
[class]{binary_search_edge}-[func]{binarySearchRightEdge}
```
=== "Swift"
```swift title="binary_search_edge.swift"
[class]{}-[func]{binarySearchRightEdge}
```
=== "Zig"
```zig title="binary_search_edge.zig"
[class]{}-[func]{binarySearchRightEdge}
```
观察下图,搜索最右元素时指针 `j` 起到了搜索最左元素时指针 `i` 的作用,反之亦然。本质上看,**搜索最左元素和最右元素的实现是镜像对称的**。
![二分查找最左元素和最右元素](binary_search_edge.assets/binary_search_left_right_edge.png)
<p align="center"> Fig. 二分查找最左元素和最右元素 </p>
!!! tip
以上代码采取的都是“双闭区间”写法。有兴趣的读者可以自行实现“左闭右开”写法。
@@ -2,7 +2,7 @@
comments: true
---
# 12.2. &nbsp; 哈希优化策略
# 10.3. &nbsp; 哈希优化策略
在算法题中,**我们常通过将线性查找替换为哈希查找来降低算法的时间复杂度**。我们借助一个算法题来加深理解。
@@ -10,7 +10,7 @@ comments: true
给定一个整数数组 `nums` 和一个整数目标值 `target` ,请在数组中搜索“和”为目标值 `target` 的两个整数,并返回他们在数组中的索引。注意,数组中同一个元素在答案里不能重复出现。返回任意一个解即可。
## 12.2.1. &nbsp; 线性查找:以时间换空间
## 10.3.1. &nbsp; 线性查找:以时间换空间
考虑直接遍历所有可能的组合。开启一个两层循环,在每轮中判断两个整数的和是否为 `target` ,若是,则返回它们的索引。
@@ -195,7 +195,7 @@ comments: true
此方法的时间复杂度为 $O(n^2)$ ,空间复杂度为 $O(1)$ ,在大数据量下非常耗时。
## 12.2.2. &nbsp; 哈希查找:以空间换时间
## 10.3.2. &nbsp; 哈希查找:以空间换时间
考虑借助一个哈希表,键值对分别为数组元素和元素索引。循环遍历数组,每轮执行:
@@ -2,13 +2,13 @@
comments: true
---
# 12.1. &nbsp; 搜索算法
# 10.4. &nbsp; 搜索算法
「搜索算法 Searching Algorithm」用于在数据结构(例如数组、链表、树或图)中搜索一个或一组满足特定条件的元素。
我们已经学过数组、链表、树和图的遍历方法,也学过哈希表、二叉搜索树等可用于实现查询的复杂数据结构。因此,搜索算法对于我们来说并不陌生。在本节,我们将从更加系统的视角切入,重新审视搜索算法。
## 12.1.1. &nbsp; 暴力搜索
## 10.4.1. &nbsp; 暴力搜索
暴力搜索通过遍历数据结构的每个元素来定位目标元素。
@@ -19,7 +19,7 @@ comments: true
然而,**此类算法的时间复杂度为 $O(n)$** ,其中 $n$ 为元素数量,因此在数据量较大的情况下性能较差。
## 12.1.2. &nbsp; 自适应搜索
## 10.4.2. &nbsp; 自适应搜索
自适应搜索利用数据的特有属性(例如有序性)来优化搜索过程,从而更高效地定位目标元素。
@@ -35,7 +35,7 @@ comments: true
自适应搜索算法常被称为查找算法,**主要关注在特定数据结构中快速检索目标元素**。
## 12.1.3. &nbsp; 搜索方法选取
## 10.4.3. &nbsp; 搜索方法选取
给定大小为 $n$ 的一组数据,我们可以使用线性搜索、二分查找、树查找、哈希查找等多种方法在该数据中搜索目标元素。各个方法的工作原理如下图所示。
+1 -1
View File
@@ -2,7 +2,7 @@
comments: true
---
# 12.3. &nbsp; 小结
# 10.5. &nbsp; 小结
- 二分查找依赖于数据的有序性,通过循环逐步缩减一半搜索区间来实现查找。它要求输入数据有序,且仅适用于数组或基于数组实现的数据结构。
- 暴力搜索通过遍历数据结构来定位数据。线性搜索适用于数组和链表,广度优先搜索和深度优先搜索适用于图和树。此类算法通用性好,无需对数据预处理,但时间复杂度 $O(n)$ 较高。