This commit is contained in:
krahets
2023-08-04 05:24:49 +08:00
parent c4046ca688
commit fafdebb75c
27 changed files with 972 additions and 536 deletions

View File

@@ -10,7 +10,11 @@ comments: true
给定一个长度为 $n$ 的数组 `nums` ,元素按从小到大的顺序排列,数组不包含重复元素。请查找并返回元素 `target` 在该数组中的索引。若数组不包含该元素,则返回 $-1$ 。
对于上述问题,我们先初始化指针 $i = 0$ 和 $j = n - 1$ ,分别指向数组首元素和尾元素,代表搜索区间 $[0, n - 1]$ 。其中,中括号表示“闭区间”,即包含边界值本身。
![二分查找示例数据](binary_search.assets/binary_search_example.png)
<p align="center"> Fig. 二分查找示例数据 </p>
对于上述问题,我们先初始化指针 $i = 0$ 和 $j = n - 1$ ,分别指向数组首元素和尾元素,代表搜索区间 $[0, n - 1]$ 。请注意,中括号表示闭区间,其包含边界值本身。
接下来,循环执行以下两个步骤:
@@ -22,9 +26,6 @@ comments: true
若数组不包含目标元素,搜索区间最终会缩小为空。此时返回 $-1$ 。
=== "<0>"
![二分查找步骤](binary_search.assets/binary_search_step0.png)
=== "<1>"
![binary_search_step1](binary_search.assets/binary_search_step1.png)

View File

@@ -1,80 +1,37 @@
---
comments: true
status: new
---
# 10.2. &nbsp; 二分查找边界
# 10.3. &nbsp; 二分查找边界
在上一节中,题目规定数组中所有元素都是唯一的。如果目标元素在数组中多次出现,上节介绍的方法只能保证返回其中一个目标元素的索引,**而无法确定该索引的左边和右边还有多少目标元素**。
## 10.3.1. &nbsp; 查找左边界
!!! question
给定一个长度为 $n$ 的有序数组 `nums` ,数组可能包含重复元素。请查找并返回元素 `target` 在数组中首次出现的索引。若数组中不包含该元素,则返回 $-1$ 。
给定一个长度为 $n$ 的有序数组 `nums` ,数组可能包含重复元素。请返回数组中最左一个元素 `target` 的索引。若数组中不包含该元素,则返回 $-1$ 。
## 10.2.1. &nbsp; 线性方法
回忆二分查找插入点的方法,搜索完成后,$i$ 指向最左一个 `target` **因此查找插入点本质上是在查找最左一个 `target` 的索引**。
为了查找数组中最左边的 `target` 我们可以分为两步
考虑通过查找插入点的函数实现查找左边界。请注意,数组中可能不包含 `target` 此时有两种可能
1. 进行二分查找,定位到任意一个 `target` 的索引,记为 $k$
2. 以索引 $k$ 为起始点,向左进行线性遍历,找到最左边的 `target` 返回即可。
1. 插入点的索引 $i$ 越界;
2. 元素 `nums[i]` `target` 不相等;
![线性查找最左边的元素](binary_search_edge.assets/binary_search_left_edge_naive.png)
<p align="center"> Fig. 线性查找最左边的元素 </p>
这个方法虽然有效,但由于包含线性查找,时间复杂度为 $O(n)$ ,当存在很多重复的 `target` 时效率较低。
## 10.2.2. &nbsp; 二分方法
考虑仅使用二分查找解决该问题。整体算法流程不变,先计算中点索引 $m$ ,再判断 `target``nums[m]` 大小关系:
-`nums[m] < target``nums[m] > target` 时,说明还没有找到 `target` ,因此采取与上节代码相同的缩小区间操作,**从而使指针 $i$ 和 $j$ 向 `target` 靠近**。
-`nums[m] == target` 时,说明“小于 `target` 的元素”在区间 $[i, m - 1]$ 中,因此采用 $j = m - 1$ 来缩小区间,**从而使指针 $j$ 向小于 `target` 的元素靠近**。
二分查找完成后,**$i$ 指向最左边的 `target` $j$ 指向首个小于 `target` 的元素**,因此返回索引 $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` 是否相等,以及索引 $i$ 是否越界。
当遇到以上两种情况时,直接返回 $-1$ 即可。
=== "Java"
```java title="binary_search_edge.java"
/* 二分查找最左一个元素 */
/* 二分查找最左一个 target */
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] 中
// 等价于查找 target 的插入点
int i = binary_search_insertion.binarySearchInsertion(nums, target);
// 未找到 target ,返回 -1
if (i == nums.length || nums[i] != target) {
return -1;
}
if (i == nums.length || nums[i] != target)
return -1; // 未找到目标元素,返回 -1
// 找到 target ,返回索引 i
return i;
}
```
@@ -82,20 +39,15 @@ comments: true
=== "C++"
```cpp title="binary_search_edge.cpp"
/* 二分查找最左一个元素 */
/* 二分查找最左一个 target */
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] 中
// 等价于查找 target 的插入点
int i = binarySearchInsertion(nums, target);
// 未找到 target ,返回 -1
if (i == nums.size() || nums[i] != target) {
return -1;
}
if (i == nums.size() || nums[i] != target)
return -1; // 未找到目标元素,返回 -1
// 找到 target ,返回索引 i
return i;
}
```
@@ -104,162 +56,50 @@ comments: true
```python title="binary_search_edge.py"
def binary_search_left_edge(nums: list[int], target: int) -> int:
"""二分查找最左一个元素"""
i, j = 0, len(nums) - 1 # 初始化双闭区间 [0, n-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] 中
"""二分查找最左一个 target"""
# 等价于查找 target 的插入点
i = binary_search_insertion(nums, target)
# 未找到 target ,返回 -1
if i == len(nums) or nums[i] != target:
return -1 # 未找到目标元素,返回 -1
return -1
# 找到 target ,返回索引 i
return i
```
=== "Go"
```go title="binary_search_edge.go"
/* 二分查找最左一个元素 */
func binarySearchLeftEdge(nums []int, target int) int {
// 初始化双闭区间 [0, n-1]
i, j := 0, len(nums)-1
for i <= j {
// 计算中点索引 m
m := 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 {
// 首个小于 target 的元素在区间 [i, m-1] 中
j = m - 1
}
}
if i == len(nums) || nums[i] != target {
// 未找到目标元素,返回 -1
return -1
}
return i
}
[class]{}-[func]{binarySearchLeftEdge}
```
=== "JS"
```javascript title="binary_search_edge.js"
/* 二分查找最左一个元素 */
function binarySearchLeftEdge(nums, target) {
let i = 0,
j = nums.length - 1; // 初始化双闭区间 [0, n-1]
while (i <= j) {
let m = Math.floor((i + j) / 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;
}
[class]{}-[func]{binarySearchLeftEdge}
```
=== "TS"
```typescript title="binary_search_edge.ts"
/* 二分查找最左一个元素 */
function binarySearchLeftEdge(nums: number[], target: number): number {
let i = 0, j = nums.length - 1; // 初始化双闭区间 [0, n-1]
while (i <= j) {
let m = Math.floor((i + j) / 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;
}
[class]{}-[func]{binarySearchLeftEdge}
```
=== "C"
```c title="binary_search_edge.c"
/* 二分查找最左一个元素 */
int binarySearchLeftEdge(int *nums, int size, int target) {
int i = 0, j = 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 == size || nums[i] != target)
return -1; // 未找到目标元素,返回 -1
return i;
}
[class]{}-[func]{binarySearchLeftEdge}
```
=== "C#"
```csharp title="binary_search_edge.cs"
/* 二分查找最左一个元素 */
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;
}
[class]{binary_search_edge}-[func]{binarySearchLeftEdge}
```
=== "Swift"
```swift title="binary_search_edge.swift"
/* 二分查找最左一个元素 */
func binarySearchLeftEdge(nums: [Int], target: Int) -> Int {
// 初始化双闭区间 [0, n-1]
var i = 0
var j = nums.count - 1
while i <= j {
let m = i + (j - 1) / 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.count || nums[i] != target {
return -1 // 未找到目标元素,返回 -1
}
return i
}
[class]{}-[func]{binarySearchLeftEdge}
```
=== "Zig"
@@ -271,70 +111,47 @@ comments: true
=== "Dart"
```dart title="binary_search_edge.dart"
/* 二分查找最左一个元素 */
int binarySearchLeftEdge(List<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;
}
[class]{}-[func]{binarySearchLeftEdge}
```
=== "Rust"
```rust title="binary_search_edge.rs"
/* 二分查找最左一个元素 */
fn binary_search_left_edge(nums: &[i32], target: i32) -> i32 {
let mut i = 0;
let mut j = nums.len() as i32 - 1; // 初始化双闭区间 [0, n-1]
while i <= j {
let m = i + (j - i) / 2; // 计算中点索引 m
if nums[m as usize] < target {
i = m + 1; // target 在区间 [m+1, j] 中
} else if nums[m as usize] > target {
j = m - 1; // target 在区间 [i, m-1] 中
} else {
j = m - 1; // 首个小于 target 的元素在区间 [i, m-1] 中
}
}
if i == nums.len() as i32 || nums[i as usize] != target {
return -1; // 未找到目标元素,返回 -1
}
i
}
[class]{}-[func]{binary_search_left_edge}
```
## 10.2.3. &nbsp; 查找右边界
## 10.3.2. &nbsp; 查找右边界
类似地,我们也可以二分查找最右边的 `target` 。当 `nums[m] == target` 时,说明大于 `target` 的元素在区间 $[m + 1, j]$ 中,因此执行 `i = m + 1` **使得指针 $i$ 向大于 `target` 的元素靠近**
那么如何查找最右一个 `target` 呢?最直接的方式是修改代码,替换在 `nums[m] == target` 情况下的指针收缩操作。代码在此省略,有兴趣的同学可以自行实现
完成二分后,**$i$ 指向首个大于 `target` 的元素,$j$ 指向最右边的 `target`** ,因此返回索引 $j$ 即可
下面我们介绍两种更加取巧的方法
### 复用查找左边界
实际上,我们可以利用查找最左元素的函数来查找最右元素,具体方法为:**将查找最右一个 `target` 转化为查找最左一个 `target + 1`**。
查找完成后,指针 $i$ 指向最左一个 `target + 1`(如果存在),而 $j$ 指向最右一个 `target` **因此返回 $j$ 即可**。
![将查找右边界转化为查找左边界](binary_search_edge.assets/binary_search_right_edge_by_left_edge.png)
<p align="center"> Fig. 将查找右边界转化为查找左边界 </p>
请注意,返回的插入点是 $i$ ,因此需要将其减 $1$ ,从而获得 $j$ 。
=== "Java"
```java title="binary_search_edge.java"
/* 二分查找最右一个元素 */
/* 二分查找最右一个 target */
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] 中
// 转化为查找最左一个 target + 1
int i = binary_search_insertion.binarySearchInsertion(nums, target + 1);
// j 指向最右一个 target i 指向首个大于 target 的元素
int j = i - 1;
// 未找到 target ,返回 -1
if (j == -1 || nums[j] != target) {
return -1;
}
if (j < 0 || nums[j] != target)
return -1; // 未找到目标元素,返回 -1
// 找到 target ,返回索引 j
return j;
}
```
@@ -342,20 +159,17 @@ comments: true
=== "C++"
```cpp title="binary_search_edge.cpp"
/* 二分查找最右一个元素 */
/* 二分查找最右一个 target */
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] 中
// 转化为查找最左一个 target + 1
int i = binarySearchInsertion(nums, target + 1);
// j 指向最右一个 target i 指向首个大于 target 的元素
int j = i - 1;
// 未找到 target ,返回 -1
if (j == -1 || nums[j] != target) {
return -1;
}
if (j < 0 || nums[j] != target)
return -1; // 未找到目标元素,返回 -1
// 找到 target ,返回索引 j
return j;
}
```
@@ -364,162 +178,52 @@ comments: true
```python title="binary_search_edge.py"
def binary_search_right_edge(nums: list[int], target: int) -> int:
"""二分查找最右一个元素"""
i, j = 0, len(nums) - 1 # 初始化双闭区间 [0, n-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 < 0 or nums[j] != target:
return -1 # 未找到目标元素,返回 -1
"""二分查找最右一个 target"""
# 转化为查找最左一个 target + 1
i = binary_search_insertion(nums, target + 1)
# j 指向最右一个 target i 指向首个大于 target 的元素
j = i - 1
# 未找到 target ,返回 -1
if j == -1 or nums[j] != target:
return -1
# 找到 target ,返回索引 j
return j
```
=== "Go"
```go title="binary_search_edge.go"
/* 二分查找最右一个元素 */
func binarySearchRightEdge(nums []int, target int) int {
// 初始化双闭区间 [0, n-1]
i, j := 0, len(nums)-1
for i <= j {
// 计算中点索引 m
m := 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 {
// 首个大于 target 的元素在区间 [m+1, j] 中
i = m + 1
}
}
if j < 0 || nums[j] != target {
// 未找到目标元素,返回 -1
return -1
}
return j
}
[class]{}-[func]{binarySearchRightEdge}
```
=== "JS"
```javascript title="binary_search_edge.js"
/* 二分查找最右一个元素 */
function binarySearchRightEdge(nums, target) {
let i = 0,
j = nums.length - 1; // 初始化双闭区间 [0, n-1]
while (i <= j) {
let m = Math.floor((i + j) / 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;
}
[class]{}-[func]{binarySearchRightEdge}
```
=== "TS"
```typescript title="binary_search_edge.ts"
/* 二分查找最右一个元素 */
function binarySearchRightEdge(nums: number[], target: number): number {
let i = 0, j = nums.length - 1; // 初始化双闭区间 [0, n-1]
while (i <= j) {
let m = Math.floor((i + j) / 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;
}
[class]{}-[func]{binarySearchRightEdge}
```
=== "C"
```c title="binary_search_edge.c"
/* 二分查找最右一个元素 */
int binarySearchRightEdge(int *nums, int size, int target) {
int i = 0, j = 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;
}
[class]{}-[func]{binarySearchRightEdge}
```
=== "C#"
```csharp title="binary_search_edge.cs"
/* 二分查找最右一个元素 */
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;
}
[class]{binary_search_edge}-[func]{binarySearchRightEdge}
```
=== "Swift"
```swift title="binary_search_edge.swift"
/* 二分查找最右一个元素 */
func binarySearchRightEdge(nums: [Int], target: Int) -> Int {
// 初始化双闭区间 [0, n-1]
var i = 0
var j = nums.count - 1
while i <= j {
let 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
}
[class]{}-[func]{binarySearchRightEdge}
```
=== "Zig"
@@ -531,53 +235,29 @@ comments: true
=== "Dart"
```dart title="binary_search_edge.dart"
/* 二分查找最右一个元素 */
int binarySearchRightEdge(List<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;
}
[class]{}-[func]{binarySearchRightEdge}
```
=== "Rust"
```rust title="binary_search_edge.rs"
/* 二分查找最右一个元素 */
fn binary_search_right_edge(nums: &[i32], target: i32) -> i32 {
let mut i = 0;
let mut j = nums.len() as i32 - 1; // 初始化双闭区间 [0, n-1]
while i <= j {
let m = i + (j - i) / 2; // 计算中点索引 m
if nums[m as usize] < target {
i = m + 1; // target 在区间 [m+1, j] 中
} else if nums[m as usize] > target {
j = m - 1; // target 在区间 [i, m-1] 中
} else {
i = m + 1; // 首个大于 target 的元素在区间 [m+1, j] 中
}
}
if j < 0 || nums[j as usize] != target {
return -1; // 未找到目标元素,返回 -1
}
j
}
[class]{}-[func]{binary_search_right_edge}
```
观察下图,搜索最右边元素时指针 $j$ 的作用与搜索最左边元素时指针 $i$ 的作用一致,反之亦然。也就是说,**搜索最左边元素和最右边元素的实现是镜像对称的**。
### 转化为查找元素
![查找最左边和最右边元素的对称性](binary_search_edge.assets/binary_search_left_right_edge.png)
我们知道,当数组不包含 `target` 时,最后 $i$ , $j$ 会分别指向首个大于、小于 `target` 的元素。
<p align="center"> Fig. 查找最左边和最右边元素的对称性 </p>
根据上述结论,我们可以构造一个数组中不存在的元素,用于查找左右边界:
!!! tip
- 查找最左一个 `target` :可以转化为查找 `target - 0.5` ,并返回指针 $i$ 。
- 查找最右一个 `target` :可以转化为查找 `target + 0.5` ,并返回指针 $j$ 。
以上代码采取的都是“双闭区间”写法。有兴趣的读者可以自行实现“左闭右开”写法。
![将查找边界转化为查找元素](binary_search_edge.assets/binary_search_edge_by_element.png)
<p align="center"> Fig. 将查找边界转化为查找元素 </p>
代码在此省略,值得注意的有:
- 给定数组不包含小数,这意味着我们无需关心如何处理相等的情况。
- 因为该方法引入了小数,所以需要将函数中的变量 `target` 改为浮点数类型。

View File

@@ -0,0 +1,320 @@
---
comments: true
status: new
---
# 10.2. &nbsp; 二分查找插入点
二分查找不仅可用于搜索目标元素,还具有许多变种问题,比如搜索目标元素的插入位置。
## 10.2.1. &nbsp; 无重复元素的情况
!!! question
给定一个长度为 $n$ 的有序数组 `nums` 和一个元素 `target` ,数组不存在重复元素。现将 `target` 插入到数组 `nums` 中,并保持其有序性。若数组中已存在元素 `target` ,则插入到其左方。请返回插入后 `target` 在数组中的索引。
![二分查找插入点示例数据](binary_search_insertion.assets/binary_search_insertion_example.png)
<p align="center"> Fig. 二分查找插入点示例数据 </p>
如果想要复用上节的二分查找代码,则需要回答以下两个问题。
**问题一**:当数组中包含 `target` 时,插入点的索引是否是该元素的索引?
题目要求将 `target` 插入到相等元素的左边,这意味着新插入的 `target` 替换了原来 `target` 的位置。也就是说,**当数组包含 `target` 时,插入点的索引就是该 `target` 的索引**。
**问题二**:当数组中不存在 `target` 时,插入点是哪个元素的索引?
进一步思考二分查找过程:当 `nums[m] < target` 时 $i$ 移动,这意味着指针 $i$ 在向大于等于 `target` 的元素靠近。同理,指针 $j$ 始终在向小于等于 `target` 的元素靠近。
因此二分结束时一定有:$i$ 指向首个大于 `target` 的元素,$j$ 指向首个小于 `target` 的元素。**易得当数组不包含 `target` 时,插入索引为 $i$** 。
=== "Java"
```java title="binary_search_insertion.java"
/* 二分查找插入点(无重复元素) */
int binarySearchInsertionSimple(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 {
return m; // 找到 target ,返回插入点 m
}
}
// 未找到 target ,返回插入点 i
return i;
}
```
=== "C++"
```cpp title="binary_search_insertion.cpp"
/* 二分查找插入点(无重复元素) */
int binarySearchInsertionSimple(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 {
return m; // 找到 target ,返回插入点 m
}
}
// 未找到 target ,返回插入点 i
return i;
}
```
=== "Python"
```python title="binary_search_insertion.py"
def binary_search_insertion_simple(nums: list[int], target: int) -> int:
"""二分查找插入点(无重复元素)"""
i, j = 0, len(nums) - 1 # 初始化双闭区间 [0, n-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:
return m # 找到 target ,返回插入点 m
# 未找到 target ,返回插入点 i
return i
```
=== "Go"
```go title="binary_search_insertion.go"
[class]{}-[func]{binarySearchInsertionSimple}
```
=== "JS"
```javascript title="binary_search_insertion.js"
[class]{}-[func]{binarySearchInsertionSimple}
```
=== "TS"
```typescript title="binary_search_insertion.ts"
[class]{}-[func]{binarySearchInsertionSimple}
```
=== "C"
```c title="binary_search_insertion.c"
[class]{}-[func]{binarySearchInsertionSimple}
```
=== "C#"
```csharp title="binary_search_insertion.cs"
[class]{binary_search_insertion}-[func]{binarySearchInsertionSimple}
```
=== "Swift"
```swift title="binary_search_insertion.swift"
[class]{}-[func]{binarySearchInsertionSimple}
```
=== "Zig"
```zig title="binary_search_insertion.zig"
[class]{}-[func]{binarySearchInsertionSimple}
```
=== "Dart"
```dart title="binary_search_insertion.dart"
[class]{}-[func]{binarySearchInsertionSimple}
```
=== "Rust"
```rust title="binary_search_insertion.rs"
[class]{}-[func]{binary_search_insertion}
```
## 10.2.2. &nbsp; 存在重复元素的情况
!!! question
在上一题的基础上,规定数组可能包含重复元素,其余不变。
假设数组中存在多个 `target` ,则普通二分查找只能返回其中一个 `target` 的索引,**而无法确定该元素的左边和右边还有多少 `target`**。
题目要求将目标元素插入到最左边,**所以我们需要查找数组中最左一个 `target` 的索引**。初步考虑通过以下两步实现:
1. 执行二分查找,得到任意一个 `target` 的索引,记为 $k$ 。
2. 从索引 $k$ 开始,向左进行线性遍历,当找到最左边的 `target` 时返回。
![线性查找重复元素的插入点](binary_search_insertion.assets/binary_search_insertion_naive.png)
<p align="center"> Fig. 线性查找重复元素的插入点 </p>
此方法虽然可用,但其包含线性查找,因此时间复杂度为 $O(n)$ 。当数组中存在很多重复的 `target` 时,该方法效率很低。
现考虑修改二分查找代码。整体流程不变,每轮先计算中点索引 $m$ ,再判断 `target` 和 `nums[m]` 大小关系:
1. 当 `nums[m] < target` 或 `nums[m] > target` 时,说明还没有找到 `target` ,因此采用普通二分查找的缩小区间操作,**从而使指针 $i$ 和 $j$ 向 `target` 靠近**。
2. 当 `nums[m] == target` 时,说明小于 `target` 的元素在区间 $[i, m - 1]$ 中,因此采用 $j = m - 1$ 来缩小区间,**从而使指针 $j$ 向小于 `target` 的元素靠近**。
循环完成后,$i$ 指向最左边的 `target` $j$ 指向首个小于 `target` 的元素,**因此索引 $i$ 就是插入点**。
=== "<1>"
![二分查找重复元素的插入点的步骤](binary_search_insertion.assets/binary_search_insertion_step1.png)
=== "<2>"
![binary_search_insertion_step2](binary_search_insertion.assets/binary_search_insertion_step2.png)
=== "<3>"
![binary_search_insertion_step3](binary_search_insertion.assets/binary_search_insertion_step3.png)
=== "<4>"
![binary_search_insertion_step4](binary_search_insertion.assets/binary_search_insertion_step4.png)
=== "<5>"
![binary_search_insertion_step5](binary_search_insertion.assets/binary_search_insertion_step5.png)
=== "<6>"
![binary_search_insertion_step6](binary_search_insertion.assets/binary_search_insertion_step6.png)
=== "<7>"
![binary_search_insertion_step7](binary_search_insertion.assets/binary_search_insertion_step7.png)
=== "<8>"
![binary_search_insertion_step8](binary_search_insertion.assets/binary_search_insertion_step8.png)
观察以下代码,判断分支 `nums[m] > target` 和 `nums[m] == target` 的操作相同,因此两者可以合并。
即便如此,我们仍然可以将判断条件保持展开,因为其逻辑更加清晰、可读性更好。
=== "Java"
```java title="binary_search_insertion.java"
/* 二分查找插入点(存在重复元素) */
int binarySearchInsertion(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] 中
}
}
// 返回插入点 i
return i;
}
```
=== "C++"
```cpp title="binary_search_insertion.cpp"
/* 二分查找插入点(存在重复元素) */
int binarySearchInsertion(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] 中
}
}
// 返回插入点 i
return i;
}
```
=== "Python"
```python title="binary_search_insertion.py"
def binary_search_insertion(nums: list[int], target: int) -> int:
"""二分查找插入点(存在重复元素)"""
i, j = 0, len(nums) - 1 # 初始化双闭区间 [0, n-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] 中
# 返回插入点 i
return i
```
=== "Go"
```go title="binary_search_insertion.go"
[class]{}-[func]{binarySearchInsertion}
```
=== "JS"
```javascript title="binary_search_insertion.js"
[class]{}-[func]{binarySearchInsertion}
```
=== "TS"
```typescript title="binary_search_insertion.ts"
[class]{}-[func]{binarySearchInsertion}
```
=== "C"
```c title="binary_search_insertion.c"
[class]{}-[func]{binarySearchInsertion}
```
=== "C#"
```csharp title="binary_search_insertion.cs"
[class]{binary_search_insertion}-[func]{binarySearchInsertion}
```
=== "Swift"
```swift title="binary_search_insertion.swift"
[class]{}-[func]{binarySearchInsertion}
```
=== "Zig"
```zig title="binary_search_insertion.zig"
[class]{}-[func]{binarySearchInsertion}
```
=== "Dart"
```dart title="binary_search_insertion.dart"
[class]{}-[func]{binarySearchInsertion}
```
=== "Rust"
```rust title="binary_search_insertion.rs"
[class]{}-[func]{binary_search_insertion}
```
!!! tip
本节的代码都是“双闭区间”写法。有兴趣的读者可以自行实现“左闭右开”写法。
总的来看,二分查找无非就是给指针 $i$ , $j$ 分别设定搜索目标,目标可能是一个具体的元素(例如 `target` ),也可能是一个元素范围(例如小于 `target` 的元素)。
在不断的循环二分中,指针 $i$ , $j$ 都逐渐逼近预先设定的目标。最终,它们或是成功找到答案,或是越过边界后停止。

View File

@@ -20,7 +20,8 @@ icon: material/text-search
## 本章内容
- [10.1 &nbsp; 二分查找](https://www.hello-algo.com/chapter_searching/binary_search/)
- [10.2 &nbsp; 二分查找边界](https://www.hello-algo.com/chapter_searching/binary_search_edge/)
- [10.3 &nbsp; 哈希优化策略](https://www.hello-algo.com/chapter_searching/replace_linear_by_hashing/)
- [10.4 &nbsp; 重识搜索算法](https://www.hello-algo.com/chapter_searching/searching_algorithm_revisited/)
- [10.5 &nbsp; 小结](https://www.hello-algo.com/chapter_searching/summary/)
- [10.2 &nbsp; 二分查找插入点](https://www.hello-algo.com/chapter_searching/binary_search_insertion/)
- [10.3 &nbsp; 二分查找边界](https://www.hello-algo.com/chapter_searching/binary_search_edge/)
- [10.4 &nbsp; 哈希优化策略](https://www.hello-algo.com/chapter_searching/replace_linear_by_hashing/)
- [10.5 &nbsp; 重识搜索算法](https://www.hello-algo.com/chapter_searching/searching_algorithm_revisited/)
- [10.6 &nbsp; 小结](https://www.hello-algo.com/chapter_searching/summary/)

View File

@@ -2,7 +2,7 @@
comments: true
---
# 10.3. &nbsp; 哈希优化策略
# 10.4. &nbsp; 哈希优化策略
在算法题中,**我们常通过将线性查找替换为哈希查找来降低算法的时间复杂度**。我们借助一个算法题来加深理解。
@@ -10,7 +10,7 @@ comments: true
给定一个整数数组 `nums` 和一个目标元素 `target` ,请在数组中搜索“和”为 `target` 的两个元素,并返回它们的数组索引。返回任意一个解即可。
## 10.3.1. &nbsp; 线性查找:以时间换空间
## 10.4.1. &nbsp; 线性查找:以时间换空间
考虑直接遍历所有可能的组合。开启一个两层循环,在每轮中判断两个整数的和是否为 `target` ,若是,则返回它们的索引。
@@ -228,7 +228,7 @@ comments: true
此方法的时间复杂度为 $O(n^2)$ ,空间复杂度为 $O(1)$ ,在大数据量下非常耗时。
## 10.3.2. &nbsp; 哈希查找:以空间换时间
## 10.4.2. &nbsp; 哈希查找:以空间换时间
考虑借助一个哈希表,键值对分别为数组元素和元素索引。循环遍历数组,每轮执行:

View File

@@ -2,7 +2,7 @@
comments: true
---
# 10.4. &nbsp; 重识搜索算法
# 10.5. &nbsp; 重识搜索算法
「搜索算法 Searching Algorithm」用于在数据结构例如数组、链表、树或图中搜索一个或一组满足特定条件的元素。
@@ -13,7 +13,7 @@ comments: true
不难发现,这些知识点都已在前面的章节中介绍过,因此搜索算法对于我们来说并不陌生。在本节中,我们将从更加系统的视角切入,重新审视搜索算法。
## 10.4.1. &nbsp; 暴力搜索
## 10.5.1. &nbsp; 暴力搜索
暴力搜索通过遍历数据结构的每个元素来定位目标元素。
@@ -24,7 +24,7 @@ comments: true
然而,**此类算法的时间复杂度为 $O(n)$** ,其中 $n$ 为元素数量,因此在数据量较大的情况下性能较差。
## 10.4.2. &nbsp; 自适应搜索
## 10.5.2. &nbsp; 自适应搜索
自适应搜索利用数据的特有属性(例如有序性)来优化搜索过程,从而更高效地定位目标元素。
@@ -40,7 +40,7 @@ comments: true
自适应搜索算法常被称为查找算法,**主要关注在特定数据结构中快速检索目标元素**。
## 10.4.3. &nbsp; 搜索方法选取
## 10.5.3. &nbsp; 搜索方法选取
给定大小为 $n$ 的一组数据,我们可以使用线性搜索、二分查找、树查找、哈希查找等多种方法在该数据中搜索目标元素。各个方法的工作原理如下图所示。

View File

@@ -2,7 +2,7 @@
comments: true
---
# 10.5. &nbsp; 小结
# 10.6. &nbsp; 小结
- 二分查找依赖于数据的有序性,通过循环逐步缩减一半搜索区间来实现查找。它要求输入数据有序,且仅适用于数组或基于数组实现的数据结构。
- 暴力搜索通过遍历数据结构来定位数据。线性搜索适用于数组和链表,广度优先搜索和深度优先搜索适用于图和树。此类算法通用性好,无需对数据预处理,但时间复杂度 $O(n)$ 较高。