mirror of
https://github.com/krahets/hello-algo.git
synced 2026-09-01 20:57:13 +00:00
build
This commit is contained in:
+721
@@ -0,0 +1,721 @@
|
||||
---
|
||||
comments: true
|
||||
---
|
||||
|
||||
# 10.1 二分搜尋
|
||||
|
||||
<u>二分搜尋(binary search)</u>是一種基於分治策略的高效搜尋演算法。它利用資料的有序性,每輪縮小一半搜尋範圍,直至找到目標元素或搜尋區間為空為止。
|
||||
|
||||
!!! question
|
||||
|
||||
給定一個長度為 $n$ 的陣列 `nums` ,元素按從小到大的順序排列且不重複。請查詢並返回元素 `target` 在該陣列中的索引。若陣列不包含該元素,則返回 $-1$ 。示例如圖 10-1 所示。
|
||||
|
||||
{ class="animation-figure" }
|
||||
|
||||
<p align="center"> 圖 10-1 二分搜尋示例資料 </p>
|
||||
|
||||
如圖 10-2 所示,我們先初始化指標 $i = 0$ 和 $j = n - 1$ ,分別指向陣列首元素和尾元素,代表搜尋區間 $[0, n - 1]$ 。請注意,中括號表示閉區間,其包含邊界值本身。
|
||||
|
||||
接下來,迴圈執行以下兩步。
|
||||
|
||||
1. 計算中點索引 $m = \lfloor {(i + j) / 2} \rfloor$ ,其中 $\lfloor \: \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` 時,說明找到 `target` ,因此返回索引 $m$ 。
|
||||
|
||||
若陣列不包含目標元素,搜尋區間最終會縮小為空。此時返回 $-1$ 。
|
||||
|
||||
=== "<1>"
|
||||
{ class="animation-figure" }
|
||||
|
||||
=== "<2>"
|
||||
{ class="animation-figure" }
|
||||
|
||||
=== "<3>"
|
||||
{ class="animation-figure" }
|
||||
|
||||
=== "<4>"
|
||||
{ class="animation-figure" }
|
||||
|
||||
=== "<5>"
|
||||
{ class="animation-figure" }
|
||||
|
||||
=== "<6>"
|
||||
{ class="animation-figure" }
|
||||
|
||||
=== "<7>"
|
||||
{ class="animation-figure" }
|
||||
|
||||
<p align="center"> 圖 10-2 二分搜尋流程 </p>
|
||||
|
||||
值得注意的是,由於 $i$ 和 $j$ 都是 `int` 型別,**因此 $i + j$ 可能會超出 `int` 型別的取值範圍**。為了避免大數越界,我們通常採用公式 $m = \lfloor {i + (j - i) / 2} \rfloor$ 來計算中點。
|
||||
|
||||
程式碼如下所示:
|
||||
|
||||
=== "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
|
||||
```
|
||||
|
||||
=== "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;
|
||||
}
|
||||
```
|
||||
|
||||
=== "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#"
|
||||
|
||||
```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;
|
||||
}
|
||||
```
|
||||
|
||||
=== "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
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="binary_search.swift"
|
||||
/* 二分搜尋(雙閉區間) */
|
||||
func binarySearch(nums: [Int], target: Int) -> Int {
|
||||
// 初始化雙閉區間 [0, n-1] ,即 i, j 分別指向陣列首元素、尾元素
|
||||
var i = nums.startIndex
|
||||
var j = nums.endIndex - 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
|
||||
}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```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;
|
||||
}
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```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
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="binary_search.dart"
|
||||
/* 二分搜尋(雙閉區間) */
|
||||
int binarySearch(List<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;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="binary_search.rs"
|
||||
/* 二分搜尋(雙閉區間) */
|
||||
fn binary_search(nums: &[i32], target: i32) -> i32 {
|
||||
// 初始化雙閉區間 [0, n-1] ,即 i, j 分別指向陣列首元素、尾元素
|
||||
let mut i = 0;
|
||||
let mut j = nums.len() as i32 - 1;
|
||||
// 迴圈,當搜尋區間為空時跳出(當 i > j 時為空)
|
||||
while i <= j {
|
||||
let m = i + (j - i) / 2; // 計算中點索引 m
|
||||
if nums[m as usize] < target {
|
||||
// 此情況說明 target 在區間 [m+1, j] 中
|
||||
i = m + 1;
|
||||
} else if nums[m as usize] > target {
|
||||
// 此情況說明 target 在區間 [i, m-1] 中
|
||||
j = m - 1;
|
||||
} else {
|
||||
// 找到目標元素,返回其索引
|
||||
return m;
|
||||
}
|
||||
}
|
||||
// 未找到目標元素,返回 -1
|
||||
return -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;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Kotlin"
|
||||
|
||||
```kotlin title="binary_search.kt"
|
||||
/* 二分搜尋(雙閉區間) */
|
||||
fun binarySearch(nums: IntArray, target: Int): Int {
|
||||
// 初始化雙閉區間 [0, n-1] ,即 i, j 分別指向陣列首元素、尾元素
|
||||
var i = 0
|
||||
var j = nums.size - 1
|
||||
// 迴圈,當搜尋區間為空時跳出(當 i > j 時為空)
|
||||
while (i <= j) {
|
||||
val 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
|
||||
}
|
||||
```
|
||||
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title="binary_search.rb"
|
||||
[class]{}-[func]{binary_search}
|
||||
```
|
||||
|
||||
=== "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(m);
|
||||
}
|
||||
}
|
||||
// 未找到目標元素,返回 -1
|
||||
return -1;
|
||||
}
|
||||
```
|
||||
|
||||
??? pythontutor "視覺化執行"
|
||||
|
||||
<div style="height: 549px; width: 100%;"><iframe class="pythontutor-iframe" src="https://pythontutor.com/iframe-embed.html#code=def%20binary_search%28nums%3A%20list%5Bint%5D,%20target%3A%20int%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%EF%BC%88%E5%8F%8C%E9%97%AD%E5%8C%BA%E9%97%B4%EF%BC%89%22%22%22%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%8F%8C%E9%97%AD%E5%8C%BA%E9%97%B4%20%5B0,%20n-1%5D%20%EF%BC%8C%E5%8D%B3%20i,%20j%20%E5%88%86%E5%88%AB%E6%8C%87%E5%90%91%E6%95%B0%E7%BB%84%E9%A6%96%E5%85%83%E7%B4%A0%E3%80%81%E5%B0%BE%E5%85%83%E7%B4%A0%0A%20%20%20%20i,%20j%20%3D%200,%20len%28nums%29%20-%201%0A%20%20%20%20%23%20%E5%BE%AA%E7%8E%AF%EF%BC%8C%E5%BD%93%E6%90%9C%E7%B4%A2%E5%8C%BA%E9%97%B4%E4%B8%BA%E7%A9%BA%E6%97%B6%E8%B7%B3%E5%87%BA%EF%BC%88%E5%BD%93%20i%20%3E%20j%20%E6%97%B6%E4%B8%BA%E7%A9%BA%EF%BC%89%0A%20%20%20%20while%20i%20%3C%3D%20j%3A%0A%20%20%20%20%20%20%20%20%23%20%E7%90%86%E8%AE%BA%E4%B8%8A%20Python%20%E7%9A%84%E6%95%B0%E5%AD%97%E5%8F%AF%E4%BB%A5%E6%97%A0%E9%99%90%E5%A4%A7%EF%BC%88%E5%8F%96%E5%86%B3%E4%BA%8E%E5%86%85%E5%AD%98%E5%A4%A7%E5%B0%8F%EF%BC%89%EF%BC%8C%E6%97%A0%E9%A1%BB%E8%80%83%E8%99%91%E5%A4%A7%E6%95%B0%E8%B6%8A%E7%95%8C%E9%97%AE%E9%A2%98%0A%20%20%20%20%20%20%20%20m%20%3D%20%28i%20%2B%20j%29%20//%202%20%20%23%20%E8%AE%A1%E7%AE%97%E4%B8%AD%E7%82%B9%E7%B4%A2%E5%BC%95%20m%0A%20%20%20%20%20%20%20%20if%20nums%5Bm%5D%20%3C%20target%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20i%20%3D%20m%20%2B%201%20%20%23%20%E6%AD%A4%E6%83%85%E5%86%B5%E8%AF%B4%E6%98%8E%20target%20%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bm%2B1,%20j%5D%20%E4%B8%AD%0A%20%20%20%20%20%20%20%20elif%20nums%5Bm%5D%20%3E%20target%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20j%20%3D%20m%20-%201%20%20%23%20%E6%AD%A4%E6%83%85%E5%86%B5%E8%AF%B4%E6%98%8E%20target%20%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bi,%20m-1%5D%20%E4%B8%AD%0A%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20return%20m%20%20%23%20%E6%89%BE%E5%88%B0%E7%9B%AE%E6%A0%87%E5%85%83%E7%B4%A0%EF%BC%8C%E8%BF%94%E5%9B%9E%E5%85%B6%E7%B4%A2%E5%BC%95%0A%20%20%20%20return%20-1%20%20%23%20%E6%9C%AA%E6%89%BE%E5%88%B0%E7%9B%AE%E6%A0%87%E5%85%83%E7%B4%A0%EF%BC%8C%E8%BF%94%E5%9B%9E%20-1%0A%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20target%20%3D%206%0A%20%20%20%20nums%20%3D%20%5B1,%203,%206,%208,%2012,%2015,%2023,%2026,%2031,%2035%5D%0A%0A%20%20%20%20%23%20%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%EF%BC%88%E5%8F%8C%E9%97%AD%E5%8C%BA%E9%97%B4%EF%BC%89%0A%20%20%20%20index%20%3D%20binary_search%28nums,%20target%29%0A%20%20%20%20print%28%22%E7%9B%AE%E6%A0%87%E5%85%83%E7%B4%A0%206%20%E7%9A%84%E7%B4%A2%E5%BC%95%20%3D%20%22,%20index%29&codeDivHeight=472&codeDivWidth=350&cumulative=false&curInstr=5&heapPrimitives=nevernest&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false"> </iframe></div>
|
||||
<div style="margin-top: 5px;"><a href="https://pythontutor.com/iframe-embed.html#code=def%20binary_search%28nums%3A%20list%5Bint%5D,%20target%3A%20int%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%EF%BC%88%E5%8F%8C%E9%97%AD%E5%8C%BA%E9%97%B4%EF%BC%89%22%22%22%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%8F%8C%E9%97%AD%E5%8C%BA%E9%97%B4%20%5B0,%20n-1%5D%20%EF%BC%8C%E5%8D%B3%20i,%20j%20%E5%88%86%E5%88%AB%E6%8C%87%E5%90%91%E6%95%B0%E7%BB%84%E9%A6%96%E5%85%83%E7%B4%A0%E3%80%81%E5%B0%BE%E5%85%83%E7%B4%A0%0A%20%20%20%20i,%20j%20%3D%200,%20len%28nums%29%20-%201%0A%20%20%20%20%23%20%E5%BE%AA%E7%8E%AF%EF%BC%8C%E5%BD%93%E6%90%9C%E7%B4%A2%E5%8C%BA%E9%97%B4%E4%B8%BA%E7%A9%BA%E6%97%B6%E8%B7%B3%E5%87%BA%EF%BC%88%E5%BD%93%20i%20%3E%20j%20%E6%97%B6%E4%B8%BA%E7%A9%BA%EF%BC%89%0A%20%20%20%20while%20i%20%3C%3D%20j%3A%0A%20%20%20%20%20%20%20%20%23%20%E7%90%86%E8%AE%BA%E4%B8%8A%20Python%20%E7%9A%84%E6%95%B0%E5%AD%97%E5%8F%AF%E4%BB%A5%E6%97%A0%E9%99%90%E5%A4%A7%EF%BC%88%E5%8F%96%E5%86%B3%E4%BA%8E%E5%86%85%E5%AD%98%E5%A4%A7%E5%B0%8F%EF%BC%89%EF%BC%8C%E6%97%A0%E9%A1%BB%E8%80%83%E8%99%91%E5%A4%A7%E6%95%B0%E8%B6%8A%E7%95%8C%E9%97%AE%E9%A2%98%0A%20%20%20%20%20%20%20%20m%20%3D%20%28i%20%2B%20j%29%20//%202%20%20%23%20%E8%AE%A1%E7%AE%97%E4%B8%AD%E7%82%B9%E7%B4%A2%E5%BC%95%20m%0A%20%20%20%20%20%20%20%20if%20nums%5Bm%5D%20%3C%20target%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20i%20%3D%20m%20%2B%201%20%20%23%20%E6%AD%A4%E6%83%85%E5%86%B5%E8%AF%B4%E6%98%8E%20target%20%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bm%2B1,%20j%5D%20%E4%B8%AD%0A%20%20%20%20%20%20%20%20elif%20nums%5Bm%5D%20%3E%20target%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20j%20%3D%20m%20-%201%20%20%23%20%E6%AD%A4%E6%83%85%E5%86%B5%E8%AF%B4%E6%98%8E%20target%20%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bi,%20m-1%5D%20%E4%B8%AD%0A%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20return%20m%20%20%23%20%E6%89%BE%E5%88%B0%E7%9B%AE%E6%A0%87%E5%85%83%E7%B4%A0%EF%BC%8C%E8%BF%94%E5%9B%9E%E5%85%B6%E7%B4%A2%E5%BC%95%0A%20%20%20%20return%20-1%20%20%23%20%E6%9C%AA%E6%89%BE%E5%88%B0%E7%9B%AE%E6%A0%87%E5%85%83%E7%B4%A0%EF%BC%8C%E8%BF%94%E5%9B%9E%20-1%0A%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20target%20%3D%206%0A%20%20%20%20nums%20%3D%20%5B1,%203,%206,%208,%2012,%2015,%2023,%2026,%2031,%2035%5D%0A%0A%20%20%20%20%23%20%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%EF%BC%88%E5%8F%8C%E9%97%AD%E5%8C%BA%E9%97%B4%EF%BC%89%0A%20%20%20%20index%20%3D%20binary_search%28nums,%20target%29%0A%20%20%20%20print%28%22%E7%9B%AE%E6%A0%87%E5%85%83%E7%B4%A0%206%20%E7%9A%84%E7%B4%A2%E5%BC%95%20%3D%20%22,%20index%29&codeDivHeight=800&codeDivWidth=600&cumulative=false&curInstr=5&heapPrimitives=nevernest&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false" target="_blank" rel="noopener noreferrer">全螢幕觀看 ></a></div>
|
||||
|
||||
**時間複雜度為 $O(\log n)$** :在二分迴圈中,區間每輪縮小一半,因此迴圈次數為 $\log_2 n$ 。
|
||||
|
||||
**空間複雜度為 $O(1)$** :指標 $i$ 和 $j$ 使用常數大小空間。
|
||||
|
||||
## 10.1.1 區間表示方法
|
||||
|
||||
除了上述雙閉區間外,常見的區間表示還有“左閉右開”區間,定義為 $[0, n)$ ,即左邊界包含自身,右邊界不包含自身。在該表示下,區間 $[i, j)$ 在 $i = j$ 時為空。
|
||||
|
||||
我們可以基於該表示實現具有相同功能的二分搜尋演算法:
|
||||
|
||||
=== "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
|
||||
```
|
||||
|
||||
=== "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;
|
||||
}
|
||||
```
|
||||
|
||||
=== "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#"
|
||||
|
||||
```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;
|
||||
}
|
||||
```
|
||||
|
||||
=== "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
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="binary_search.swift"
|
||||
/* 二分搜尋(左閉右開區間) */
|
||||
func binarySearchLCRO(nums: [Int], target: Int) -> Int {
|
||||
// 初始化左閉右開區間 [0, n) ,即 i, j 分別指向陣列首元素、尾元素+1
|
||||
var i = nums.startIndex
|
||||
var j = nums.endIndex
|
||||
// 迴圈,當搜尋區間為空時跳出(當 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
|
||||
}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```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;
|
||||
}
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```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
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="binary_search.dart"
|
||||
/* 二分搜尋(左閉右開區間) */
|
||||
int binarySearchLCRO(List<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;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="binary_search.rs"
|
||||
/* 二分搜尋(左閉右開區間) */
|
||||
fn binary_search_lcro(nums: &[i32], target: i32) -> i32 {
|
||||
// 初始化左閉右開區間 [0, n) ,即 i, j 分別指向陣列首元素、尾元素+1
|
||||
let mut i = 0;
|
||||
let mut j = nums.len() as i32;
|
||||
// 迴圈,當搜尋區間為空時跳出(當 i = j 時為空)
|
||||
while i < j {
|
||||
let m = i + (j - i) / 2; // 計算中點索引 m
|
||||
if nums[m as usize] < target {
|
||||
// 此情況說明 target 在區間 [m+1, j) 中
|
||||
i = m + 1;
|
||||
} else if nums[m as usize] > target {
|
||||
// 此情況說明 target 在區間 [i, m) 中
|
||||
j = m;
|
||||
} else {
|
||||
// 找到目標元素,返回其索引
|
||||
return m;
|
||||
}
|
||||
}
|
||||
// 未找到目標元素,返回 -1
|
||||
return -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;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Kotlin"
|
||||
|
||||
```kotlin title="binary_search.kt"
|
||||
/* 二分搜尋(左閉右開區間) */
|
||||
fun binarySearchLCRO(nums: IntArray, target: Int): Int {
|
||||
// 初始化左閉右開區間 [0, n) ,即 i, j 分別指向陣列首元素、尾元素+1
|
||||
var i = 0
|
||||
var j = nums.size
|
||||
// 迴圈,當搜尋區間為空時跳出(當 i = j 時為空)
|
||||
while (i < j) {
|
||||
val 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
|
||||
}
|
||||
```
|
||||
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title="binary_search.rb"
|
||||
[class]{}-[func]{binary_search_lcro}
|
||||
```
|
||||
|
||||
=== "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(m);
|
||||
}
|
||||
}
|
||||
// 未找到目標元素,返回 -1
|
||||
return -1;
|
||||
}
|
||||
```
|
||||
|
||||
??? pythontutor "視覺化執行"
|
||||
|
||||
<div style="height: 549px; width: 100%;"><iframe class="pythontutor-iframe" src="https://pythontutor.com/iframe-embed.html#code=def%20binary_search_lcro%28nums%3A%20list%5Bint%5D,%20target%3A%20int%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%EF%BC%88%E5%B7%A6%E9%97%AD%E5%8F%B3%E5%BC%80%E5%8C%BA%E9%97%B4%EF%BC%89%22%22%22%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%B7%A6%E9%97%AD%E5%8F%B3%E5%BC%80%E5%8C%BA%E9%97%B4%20%5B0,%20n%29%20%EF%BC%8C%E5%8D%B3%20i,%20j%20%E5%88%86%E5%88%AB%E6%8C%87%E5%90%91%E6%95%B0%E7%BB%84%E9%A6%96%E5%85%83%E7%B4%A0%E3%80%81%E5%B0%BE%E5%85%83%E7%B4%A0%2B1%0A%20%20%20%20i,%20j%20%3D%200,%20len%28nums%29%0A%20%20%20%20%23%20%E5%BE%AA%E7%8E%AF%EF%BC%8C%E5%BD%93%E6%90%9C%E7%B4%A2%E5%8C%BA%E9%97%B4%E4%B8%BA%E7%A9%BA%E6%97%B6%E8%B7%B3%E5%87%BA%EF%BC%88%E5%BD%93%20i%20%3D%20j%20%E6%97%B6%E4%B8%BA%E7%A9%BA%EF%BC%89%0A%20%20%20%20while%20i%20%3C%20j%3A%0A%20%20%20%20%20%20%20%20m%20%3D%20%28i%20%2B%20j%29%20//%202%20%20%23%20%E8%AE%A1%E7%AE%97%E4%B8%AD%E7%82%B9%E7%B4%A2%E5%BC%95%20m%0A%20%20%20%20%20%20%20%20if%20nums%5Bm%5D%20%3C%20target%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20i%20%3D%20m%20%2B%201%20%20%23%20%E6%AD%A4%E6%83%85%E5%86%B5%E8%AF%B4%E6%98%8E%20target%20%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bm%2B1,%20j%29%20%E4%B8%AD%0A%20%20%20%20%20%20%20%20elif%20nums%5Bm%5D%20%3E%20target%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20j%20%3D%20m%20%20%23%20%E6%AD%A4%E6%83%85%E5%86%B5%E8%AF%B4%E6%98%8E%20target%20%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bi,%20m%29%20%E4%B8%AD%0A%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20return%20m%20%20%23%20%E6%89%BE%E5%88%B0%E7%9B%AE%E6%A0%87%E5%85%83%E7%B4%A0%EF%BC%8C%E8%BF%94%E5%9B%9E%E5%85%B6%E7%B4%A2%E5%BC%95%0A%20%20%20%20return%20-1%20%20%23%20%E6%9C%AA%E6%89%BE%E5%88%B0%E7%9B%AE%E6%A0%87%E5%85%83%E7%B4%A0%EF%BC%8C%E8%BF%94%E5%9B%9E%20-1%0A%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20target%20%3D%206%0A%20%20%20%20nums%20%3D%20%5B1,%203,%206,%208,%2012,%2015,%2023,%2026,%2031,%2035%5D%0A%0A%20%20%20%20%23%20%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%EF%BC%88%E5%B7%A6%E9%97%AD%E5%8F%B3%E5%BC%80%E5%8C%BA%E9%97%B4%EF%BC%89%0A%20%20%20%20index%20%3D%20binary_search_lcro%28nums,%20target%29%0A%20%20%20%20print%28%22%E7%9B%AE%E6%A0%87%E5%85%83%E7%B4%A0%206%20%E7%9A%84%E7%B4%A2%E5%BC%95%20%3D%20%22,%20index%29&codeDivHeight=472&codeDivWidth=350&cumulative=false&curInstr=5&heapPrimitives=nevernest&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false"> </iframe></div>
|
||||
<div style="margin-top: 5px;"><a href="https://pythontutor.com/iframe-embed.html#code=def%20binary_search_lcro%28nums%3A%20list%5Bint%5D,%20target%3A%20int%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%EF%BC%88%E5%B7%A6%E9%97%AD%E5%8F%B3%E5%BC%80%E5%8C%BA%E9%97%B4%EF%BC%89%22%22%22%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%B7%A6%E9%97%AD%E5%8F%B3%E5%BC%80%E5%8C%BA%E9%97%B4%20%5B0,%20n%29%20%EF%BC%8C%E5%8D%B3%20i,%20j%20%E5%88%86%E5%88%AB%E6%8C%87%E5%90%91%E6%95%B0%E7%BB%84%E9%A6%96%E5%85%83%E7%B4%A0%E3%80%81%E5%B0%BE%E5%85%83%E7%B4%A0%2B1%0A%20%20%20%20i,%20j%20%3D%200,%20len%28nums%29%0A%20%20%20%20%23%20%E5%BE%AA%E7%8E%AF%EF%BC%8C%E5%BD%93%E6%90%9C%E7%B4%A2%E5%8C%BA%E9%97%B4%E4%B8%BA%E7%A9%BA%E6%97%B6%E8%B7%B3%E5%87%BA%EF%BC%88%E5%BD%93%20i%20%3D%20j%20%E6%97%B6%E4%B8%BA%E7%A9%BA%EF%BC%89%0A%20%20%20%20while%20i%20%3C%20j%3A%0A%20%20%20%20%20%20%20%20m%20%3D%20%28i%20%2B%20j%29%20//%202%20%20%23%20%E8%AE%A1%E7%AE%97%E4%B8%AD%E7%82%B9%E7%B4%A2%E5%BC%95%20m%0A%20%20%20%20%20%20%20%20if%20nums%5Bm%5D%20%3C%20target%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20i%20%3D%20m%20%2B%201%20%20%23%20%E6%AD%A4%E6%83%85%E5%86%B5%E8%AF%B4%E6%98%8E%20target%20%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bm%2B1,%20j%29%20%E4%B8%AD%0A%20%20%20%20%20%20%20%20elif%20nums%5Bm%5D%20%3E%20target%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20j%20%3D%20m%20%20%23%20%E6%AD%A4%E6%83%85%E5%86%B5%E8%AF%B4%E6%98%8E%20target%20%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bi,%20m%29%20%E4%B8%AD%0A%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20return%20m%20%20%23%20%E6%89%BE%E5%88%B0%E7%9B%AE%E6%A0%87%E5%85%83%E7%B4%A0%EF%BC%8C%E8%BF%94%E5%9B%9E%E5%85%B6%E7%B4%A2%E5%BC%95%0A%20%20%20%20return%20-1%20%20%23%20%E6%9C%AA%E6%89%BE%E5%88%B0%E7%9B%AE%E6%A0%87%E5%85%83%E7%B4%A0%EF%BC%8C%E8%BF%94%E5%9B%9E%20-1%0A%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20target%20%3D%206%0A%20%20%20%20nums%20%3D%20%5B1,%203,%206,%208,%2012,%2015,%2023,%2026,%2031,%2035%5D%0A%0A%20%20%20%20%23%20%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%EF%BC%88%E5%B7%A6%E9%97%AD%E5%8F%B3%E5%BC%80%E5%8C%BA%E9%97%B4%EF%BC%89%0A%20%20%20%20index%20%3D%20binary_search_lcro%28nums,%20target%29%0A%20%20%20%20print%28%22%E7%9B%AE%E6%A0%87%E5%85%83%E7%B4%A0%206%20%E7%9A%84%E7%B4%A2%E5%BC%95%20%3D%20%22,%20index%29&codeDivHeight=800&codeDivWidth=600&cumulative=false&curInstr=5&heapPrimitives=nevernest&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false" target="_blank" rel="noopener noreferrer">全螢幕觀看 ></a></div>
|
||||
|
||||
如圖 10-3 所示,在兩種區間表示下,二分搜尋演算法的初始化、迴圈條件和縮小區間操作皆有所不同。
|
||||
|
||||
由於“雙閉區間”表示中的左右邊界都被定義為閉區間,因此透過指標 $i$ 和指標 $j$ 縮小區間的操作也是對稱的。這樣更不容易出錯,**因此一般建議採用“雙閉區間”的寫法**。
|
||||
|
||||
{ class="animation-figure" }
|
||||
|
||||
<p align="center"> 圖 10-3 兩種區間定義 </p>
|
||||
|
||||
## 10.1.2 優點與侷限性
|
||||
|
||||
二分搜尋在時間和空間方面都有較好的效能。
|
||||
|
||||
- 二分搜尋的時間效率高。在大資料量下,對數階的時間複雜度具有顯著優勢。例如,當資料大小 $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$ 較小時,線性查詢反而比二分搜尋更快。
|
||||
@@ -0,0 +1,494 @@
|
||||
---
|
||||
comments: true
|
||||
---
|
||||
|
||||
# 10.3 二分搜尋邊界
|
||||
|
||||
## 10.3.1 查詢左邊界
|
||||
|
||||
!!! question
|
||||
|
||||
給定一個長度為 $n$ 的有序陣列 `nums` ,其中可能包含重複元素。請返回陣列中最左一個元素 `target` 的索引。若陣列中不包含該元素,則返回 $-1$ 。
|
||||
|
||||
回憶二分搜尋插入點的方法,搜尋完成後 $i$ 指向最左一個 `target` ,**因此查詢插入點本質上是在查詢最左一個 `target` 的索引**。
|
||||
|
||||
考慮透過查詢插入點的函式實現查詢左邊界。請注意,陣列中可能不包含 `target` ,這種情況可能導致以下兩種結果。
|
||||
|
||||
- 插入點的索引 $i$ 越界。
|
||||
- 元素 `nums[i]` 與 `target` 不相等。
|
||||
|
||||
當遇到以上兩種情況時,直接返回 $-1$ 即可。程式碼如下所示:
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="binary_search_edge.py"
|
||||
def binary_search_left_edge(nums: list[int], target: int) -> int:
|
||||
"""二分搜尋最左一個 target"""
|
||||
# 等價於查詢 target 的插入點
|
||||
i = binary_search_insertion(nums, target)
|
||||
# 未找到 target ,返回 -1
|
||||
if i == len(nums) or nums[i] != target:
|
||||
return -1
|
||||
# 找到 target ,返回索引 i
|
||||
return i
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="binary_search_edge.cpp"
|
||||
/* 二分搜尋最左一個 target */
|
||||
int binarySearchLeftEdge(vector<int> &nums, int target) {
|
||||
// 等價於查詢 target 的插入點
|
||||
int i = binarySearchInsertion(nums, target);
|
||||
// 未找到 target ,返回 -1
|
||||
if (i == nums.size() || nums[i] != target) {
|
||||
return -1;
|
||||
}
|
||||
// 找到 target ,返回索引 i
|
||||
return i;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="binary_search_edge.java"
|
||||
/* 二分搜尋最左一個 target */
|
||||
int binarySearchLeftEdge(int[] nums, int target) {
|
||||
// 等價於查詢 target 的插入點
|
||||
int i = binary_search_insertion.binarySearchInsertion(nums, target);
|
||||
// 未找到 target ,返回 -1
|
||||
if (i == nums.length || nums[i] != target) {
|
||||
return -1;
|
||||
}
|
||||
// 找到 target ,返回索引 i
|
||||
return i;
|
||||
}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="binary_search_edge.cs"
|
||||
/* 二分搜尋最左一個 target */
|
||||
int BinarySearchLeftEdge(int[] nums, int target) {
|
||||
// 等價於查詢 target 的插入點
|
||||
int i = binary_search_insertion.BinarySearchInsertion(nums, target);
|
||||
// 未找到 target ,返回 -1
|
||||
if (i == nums.Length || nums[i] != target) {
|
||||
return -1;
|
||||
}
|
||||
// 找到 target ,返回索引 i
|
||||
return i;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="binary_search_edge.go"
|
||||
/* 二分搜尋最左一個 target */
|
||||
func binarySearchLeftEdge(nums []int, target int) int {
|
||||
// 等價於查詢 target 的插入點
|
||||
i := binarySearchInsertion(nums, target)
|
||||
// 未找到 target ,返回 -1
|
||||
if i == len(nums) || nums[i] != target {
|
||||
return -1
|
||||
}
|
||||
// 找到 target ,返回索引 i
|
||||
return i
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="binary_search_edge.swift"
|
||||
/* 二分搜尋最左一個 target */
|
||||
func binarySearchLeftEdge(nums: [Int], target: Int) -> Int {
|
||||
// 等價於查詢 target 的插入點
|
||||
let i = binarySearchInsertion(nums: nums, target: target)
|
||||
// 未找到 target ,返回 -1
|
||||
if i == nums.endIndex || nums[i] != target {
|
||||
return -1
|
||||
}
|
||||
// 找到 target ,返回索引 i
|
||||
return i
|
||||
}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="binary_search_edge.js"
|
||||
/* 二分搜尋最左一個 target */
|
||||
function binarySearchLeftEdge(nums, target) {
|
||||
// 等價於查詢 target 的插入點
|
||||
const i = binarySearchInsertion(nums, target);
|
||||
// 未找到 target ,返回 -1
|
||||
if (i === nums.length || nums[i] !== target) {
|
||||
return -1;
|
||||
}
|
||||
// 找到 target ,返回索引 i
|
||||
return i;
|
||||
}
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```typescript title="binary_search_edge.ts"
|
||||
/* 二分搜尋最左一個 target */
|
||||
function binarySearchLeftEdge(nums: Array<number>, target: number): number {
|
||||
// 等價於查詢 target 的插入點
|
||||
const i = binarySearchInsertion(nums, target);
|
||||
// 未找到 target ,返回 -1
|
||||
if (i === nums.length || nums[i] !== target) {
|
||||
return -1;
|
||||
}
|
||||
// 找到 target ,返回索引 i
|
||||
return i;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="binary_search_edge.dart"
|
||||
/* 二分搜尋最左一個 target */
|
||||
int binarySearchLeftEdge(List<int> nums, int target) {
|
||||
// 等價於查詢 target 的插入點
|
||||
int i = binarySearchInsertion(nums, target);
|
||||
// 未找到 target ,返回 -1
|
||||
if (i == nums.length || nums[i] != target) {
|
||||
return -1;
|
||||
}
|
||||
// 找到 target ,返回索引 i
|
||||
return i;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="binary_search_edge.rs"
|
||||
/* 二分搜尋最左一個 target */
|
||||
fn binary_search_left_edge(nums: &[i32], target: i32) -> i32 {
|
||||
// 等價於查詢 target 的插入點
|
||||
let i = binary_search_insertion(nums, target);
|
||||
// 未找到 target ,返回 -1
|
||||
if i == nums.len() as i32 || nums[i as usize] != target {
|
||||
return -1;
|
||||
}
|
||||
// 找到 target ,返回索引 i
|
||||
i
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="binary_search_edge.c"
|
||||
/* 二分搜尋最左一個 target */
|
||||
int binarySearchLeftEdge(int *nums, int numSize, int target) {
|
||||
// 等價於查詢 target 的插入點
|
||||
int i = binarySearchInsertion(nums, numSize, target);
|
||||
// 未找到 target ,返回 -1
|
||||
if (i == numSize || nums[i] != target) {
|
||||
return -1;
|
||||
}
|
||||
// 找到 target ,返回索引 i
|
||||
return i;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Kotlin"
|
||||
|
||||
```kotlin title="binary_search_edge.kt"
|
||||
/* 二分搜尋最左一個 target */
|
||||
fun binarySearchLeftEdge(nums: IntArray, target: Int): Int {
|
||||
// 等價於查詢 target 的插入點
|
||||
val i = binarySearchInsertion(nums, target)
|
||||
// 未找到 target ,返回 -1
|
||||
if (i == nums.size || nums[i] != target) {
|
||||
return -1
|
||||
}
|
||||
// 找到 target ,返回索引 i
|
||||
return i
|
||||
}
|
||||
```
|
||||
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title="binary_search_edge.rb"
|
||||
[class]{}-[func]{binary_search_left_edge}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="binary_search_edge.zig"
|
||||
[class]{}-[func]{binarySearchLeftEdge}
|
||||
```
|
||||
|
||||
??? pythontutor "視覺化執行"
|
||||
|
||||
<div style="height: 549px; width: 100%;"><iframe class="pythontutor-iframe" src="https://pythontutor.com/iframe-embed.html#code=def%20binary_search_insertion%28nums%3A%20list%5Bint%5D,%20target%3A%20int%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E6%8F%92%E5%85%A5%E7%82%B9%EF%BC%88%E5%AD%98%E5%9C%A8%E9%87%8D%E5%A4%8D%E5%85%83%E7%B4%A0%EF%BC%89%22%22%22%0A%20%20%20%20i,%20j%20%3D%200,%20len%28nums%29%20-%201%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%8F%8C%E9%97%AD%E5%8C%BA%E9%97%B4%20%5B0,%20n-1%5D%0A%20%20%20%20while%20i%20%3C%3D%20j%3A%0A%20%20%20%20%20%20%20%20m%20%3D%20%28i%20%2B%20j%29%20//%202%20%20%23%20%E8%AE%A1%E7%AE%97%E4%B8%AD%E7%82%B9%E7%B4%A2%E5%BC%95%20m%0A%20%20%20%20%20%20%20%20if%20nums%5Bm%5D%20%3C%20target%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20i%20%3D%20m%20%2B%201%20%20%23%20target%20%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bm%2B1,%20j%5D%20%E4%B8%AD%0A%20%20%20%20%20%20%20%20elif%20nums%5Bm%5D%20%3E%20target%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20j%20%3D%20m%20-%201%20%20%23%20target%20%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bi,%20m-1%5D%20%E4%B8%AD%0A%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20j%20%3D%20m%20-%201%20%20%23%20%E9%A6%96%E4%B8%AA%E5%B0%8F%E4%BA%8E%20target%20%E7%9A%84%E5%85%83%E7%B4%A0%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bi,%20m-1%5D%20%E4%B8%AD%0A%20%20%20%20%23%20%E8%BF%94%E5%9B%9E%E6%8F%92%E5%85%A5%E7%82%B9%20i%0A%20%20%20%20return%20i%0A%0Adef%20binary_search_left_edge%28nums%3A%20list%5Bint%5D,%20target%3A%20int%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E6%9C%80%E5%B7%A6%E4%B8%80%E4%B8%AA%20target%22%22%22%0A%20%20%20%20%23%20%E7%AD%89%E4%BB%B7%E4%BA%8E%E6%9F%A5%E6%89%BE%20target%20%E7%9A%84%E6%8F%92%E5%85%A5%E7%82%B9%0A%20%20%20%20i%20%3D%20binary_search_insertion%28nums,%20target%29%0A%20%20%20%20%23%20%E6%9C%AA%E6%89%BE%E5%88%B0%20target%20%EF%BC%8C%E8%BF%94%E5%9B%9E%20-1%0A%20%20%20%20if%20i%20%3D%3D%20len%28nums%29%20or%20nums%5Bi%5D%20!%3D%20target%3A%0A%20%20%20%20%20%20%20%20return%20-1%0A%20%20%20%20%23%20%E6%89%BE%E5%88%B0%20target%20%EF%BC%8C%E8%BF%94%E5%9B%9E%E7%B4%A2%E5%BC%95%20i%0A%20%20%20%20return%20i%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%8C%85%E5%90%AB%E9%87%8D%E5%A4%8D%E5%85%83%E7%B4%A0%E7%9A%84%E6%95%B0%E7%BB%84%0A%20%20%20%20nums%20%3D%20%5B1,%203,%206,%206,%206,%206,%206,%2010,%2012,%2015%5D%0A%20%20%20%20%23%20%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E5%B7%A6%E8%BE%B9%E7%95%8C%E5%92%8C%E5%8F%B3%E8%BE%B9%E7%95%8C%0A%20%20%20%20target%20%3D%206%0A%20%20%20%20index%20%3D%20binary_search_left_edge%28nums,%20target%29%0A%20%20%20%20print%28f%22%E6%9C%80%E5%B7%A6%E4%B8%80%E4%B8%AA%E5%85%83%E7%B4%A0%20%7Btarget%7D%20%E7%9A%84%E7%B4%A2%E5%BC%95%E4%B8%BA%20%7Bindex%7D%22%29&codeDivHeight=472&codeDivWidth=350&cumulative=false&curInstr=6&heapPrimitives=nevernest&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false"> </iframe></div>
|
||||
<div style="margin-top: 5px;"><a href="https://pythontutor.com/iframe-embed.html#code=def%20binary_search_insertion%28nums%3A%20list%5Bint%5D,%20target%3A%20int%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E6%8F%92%E5%85%A5%E7%82%B9%EF%BC%88%E5%AD%98%E5%9C%A8%E9%87%8D%E5%A4%8D%E5%85%83%E7%B4%A0%EF%BC%89%22%22%22%0A%20%20%20%20i,%20j%20%3D%200,%20len%28nums%29%20-%201%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%8F%8C%E9%97%AD%E5%8C%BA%E9%97%B4%20%5B0,%20n-1%5D%0A%20%20%20%20while%20i%20%3C%3D%20j%3A%0A%20%20%20%20%20%20%20%20m%20%3D%20%28i%20%2B%20j%29%20//%202%20%20%23%20%E8%AE%A1%E7%AE%97%E4%B8%AD%E7%82%B9%E7%B4%A2%E5%BC%95%20m%0A%20%20%20%20%20%20%20%20if%20nums%5Bm%5D%20%3C%20target%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20i%20%3D%20m%20%2B%201%20%20%23%20target%20%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bm%2B1,%20j%5D%20%E4%B8%AD%0A%20%20%20%20%20%20%20%20elif%20nums%5Bm%5D%20%3E%20target%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20j%20%3D%20m%20-%201%20%20%23%20target%20%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bi,%20m-1%5D%20%E4%B8%AD%0A%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20j%20%3D%20m%20-%201%20%20%23%20%E9%A6%96%E4%B8%AA%E5%B0%8F%E4%BA%8E%20target%20%E7%9A%84%E5%85%83%E7%B4%A0%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bi,%20m-1%5D%20%E4%B8%AD%0A%20%20%20%20%23%20%E8%BF%94%E5%9B%9E%E6%8F%92%E5%85%A5%E7%82%B9%20i%0A%20%20%20%20return%20i%0A%0Adef%20binary_search_left_edge%28nums%3A%20list%5Bint%5D,%20target%3A%20int%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E6%9C%80%E5%B7%A6%E4%B8%80%E4%B8%AA%20target%22%22%22%0A%20%20%20%20%23%20%E7%AD%89%E4%BB%B7%E4%BA%8E%E6%9F%A5%E6%89%BE%20target%20%E7%9A%84%E6%8F%92%E5%85%A5%E7%82%B9%0A%20%20%20%20i%20%3D%20binary_search_insertion%28nums,%20target%29%0A%20%20%20%20%23%20%E6%9C%AA%E6%89%BE%E5%88%B0%20target%20%EF%BC%8C%E8%BF%94%E5%9B%9E%20-1%0A%20%20%20%20if%20i%20%3D%3D%20len%28nums%29%20or%20nums%5Bi%5D%20!%3D%20target%3A%0A%20%20%20%20%20%20%20%20return%20-1%0A%20%20%20%20%23%20%E6%89%BE%E5%88%B0%20target%20%EF%BC%8C%E8%BF%94%E5%9B%9E%E7%B4%A2%E5%BC%95%20i%0A%20%20%20%20return%20i%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%8C%85%E5%90%AB%E9%87%8D%E5%A4%8D%E5%85%83%E7%B4%A0%E7%9A%84%E6%95%B0%E7%BB%84%0A%20%20%20%20nums%20%3D%20%5B1,%203,%206,%206,%206,%206,%206,%2010,%2012,%2015%5D%0A%20%20%20%20%23%20%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E5%B7%A6%E8%BE%B9%E7%95%8C%E5%92%8C%E5%8F%B3%E8%BE%B9%E7%95%8C%0A%20%20%20%20target%20%3D%206%0A%20%20%20%20index%20%3D%20binary_search_left_edge%28nums,%20target%29%0A%20%20%20%20print%28f%22%E6%9C%80%E5%B7%A6%E4%B8%80%E4%B8%AA%E5%85%83%E7%B4%A0%20%7Btarget%7D%20%E7%9A%84%E7%B4%A2%E5%BC%95%E4%B8%BA%20%7Bindex%7D%22%29&codeDivHeight=800&codeDivWidth=600&cumulative=false&curInstr=6&heapPrimitives=nevernest&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false" target="_blank" rel="noopener noreferrer">全螢幕觀看 ></a></div>
|
||||
|
||||
## 10.3.2 查詢右邊界
|
||||
|
||||
那麼如何查詢最右一個 `target` 呢?最直接的方式是修改程式碼,替換在 `nums[m] == target` 情況下的指標收縮操作。程式碼在此省略,有興趣的讀者可以自行實現。
|
||||
|
||||
下面我們介紹兩種更加取巧的方法。
|
||||
|
||||
### 1. 複用查詢左邊界
|
||||
|
||||
實際上,我們可以利用查詢最左元素的函式來查詢最右元素,具體方法為:**將查詢最右一個 `target` 轉化為查詢最左一個 `target + 1`**。
|
||||
|
||||
如圖 10-7 所示,查詢完成後,指標 $i$ 指向最左一個 `target + 1`(如果存在),而 $j$ 指向最右一個 `target` ,**因此返回 $j$ 即可**。
|
||||
|
||||
{ class="animation-figure" }
|
||||
|
||||
<p align="center"> 圖 10-7 將查詢右邊界轉化為查詢左邊界 </p>
|
||||
|
||||
請注意,返回的插入點是 $i$ ,因此需要將其減 $1$ ,從而獲得 $j$ :
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="binary_search_edge.py"
|
||||
def binary_search_right_edge(nums: list[int], target: int) -> int:
|
||||
"""二分搜尋最右一個 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
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="binary_search_edge.cpp"
|
||||
/* 二分搜尋最右一個 target */
|
||||
int binarySearchRightEdge(vector<int> &nums, int target) {
|
||||
// 轉化為查詢最左一個 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;
|
||||
}
|
||||
// 找到 target ,返回索引 j
|
||||
return j;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="binary_search_edge.java"
|
||||
/* 二分搜尋最右一個 target */
|
||||
int binarySearchRightEdge(int[] nums, int target) {
|
||||
// 轉化為查詢最左一個 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;
|
||||
}
|
||||
// 找到 target ,返回索引 j
|
||||
return j;
|
||||
}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="binary_search_edge.cs"
|
||||
/* 二分搜尋最右一個 target */
|
||||
int BinarySearchRightEdge(int[] nums, int target) {
|
||||
// 轉化為查詢最左一個 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;
|
||||
}
|
||||
// 找到 target ,返回索引 j
|
||||
return j;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="binary_search_edge.go"
|
||||
/* 二分搜尋最右一個 target */
|
||||
func binarySearchRightEdge(nums []int, target int) int {
|
||||
// 轉化為查詢最左一個 target + 1
|
||||
i := binarySearchInsertion(nums, target+1)
|
||||
// j 指向最右一個 target ,i 指向首個大於 target 的元素
|
||||
j := i - 1
|
||||
// 未找到 target ,返回 -1
|
||||
if j == -1 || nums[j] != target {
|
||||
return -1
|
||||
}
|
||||
// 找到 target ,返回索引 j
|
||||
return j
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="binary_search_edge.swift"
|
||||
/* 二分搜尋最右一個 target */
|
||||
func binarySearchRightEdge(nums: [Int], target: Int) -> Int {
|
||||
// 轉化為查詢最左一個 target + 1
|
||||
let i = binarySearchInsertion(nums: nums, target: target + 1)
|
||||
// j 指向最右一個 target ,i 指向首個大於 target 的元素
|
||||
let j = i - 1
|
||||
// 未找到 target ,返回 -1
|
||||
if j == -1 || nums[j] != target {
|
||||
return -1
|
||||
}
|
||||
// 找到 target ,返回索引 j
|
||||
return j
|
||||
}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="binary_search_edge.js"
|
||||
/* 二分搜尋最右一個 target */
|
||||
function binarySearchRightEdge(nums, target) {
|
||||
// 轉化為查詢最左一個 target + 1
|
||||
const i = binarySearchInsertion(nums, target + 1);
|
||||
// j 指向最右一個 target ,i 指向首個大於 target 的元素
|
||||
const j = i - 1;
|
||||
// 未找到 target ,返回 -1
|
||||
if (j === -1 || nums[j] !== target) {
|
||||
return -1;
|
||||
}
|
||||
// 找到 target ,返回索引 j
|
||||
return j;
|
||||
}
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```typescript title="binary_search_edge.ts"
|
||||
/* 二分搜尋最右一個 target */
|
||||
function binarySearchRightEdge(nums: Array<number>, target: number): number {
|
||||
// 轉化為查詢最左一個 target + 1
|
||||
const i = binarySearchInsertion(nums, target + 1);
|
||||
// j 指向最右一個 target ,i 指向首個大於 target 的元素
|
||||
const j = i - 1;
|
||||
// 未找到 target ,返回 -1
|
||||
if (j === -1 || nums[j] !== target) {
|
||||
return -1;
|
||||
}
|
||||
// 找到 target ,返回索引 j
|
||||
return j;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="binary_search_edge.dart"
|
||||
/* 二分搜尋最右一個 target */
|
||||
int binarySearchRightEdge(List<int> nums, int target) {
|
||||
// 轉化為查詢最左一個 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;
|
||||
}
|
||||
// 找到 target ,返回索引 j
|
||||
return j;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="binary_search_edge.rs"
|
||||
/* 二分搜尋最右一個 target */
|
||||
fn binary_search_right_edge(nums: &[i32], target: i32) -> i32 {
|
||||
// 轉化為查詢最左一個 target + 1
|
||||
let i = binary_search_insertion(nums, target + 1);
|
||||
// j 指向最右一個 target ,i 指向首個大於 target 的元素
|
||||
let j = i - 1;
|
||||
// 未找到 target ,返回 -1
|
||||
if j == -1 || nums[j as usize] != target {
|
||||
return -1;
|
||||
}
|
||||
// 找到 target ,返回索引 j
|
||||
j
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="binary_search_edge.c"
|
||||
/* 二分搜尋最右一個 target */
|
||||
int binarySearchRightEdge(int *nums, int numSize, int target) {
|
||||
// 轉化為查詢最左一個 target + 1
|
||||
int i = binarySearchInsertion(nums, numSize, target + 1);
|
||||
// j 指向最右一個 target ,i 指向首個大於 target 的元素
|
||||
int j = i - 1;
|
||||
// 未找到 target ,返回 -1
|
||||
if (j == -1 || nums[j] != target) {
|
||||
return -1;
|
||||
}
|
||||
// 找到 target ,返回索引 j
|
||||
return j;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Kotlin"
|
||||
|
||||
```kotlin title="binary_search_edge.kt"
|
||||
/* 二分搜尋最右一個 target */
|
||||
fun binarySearchRightEdge(nums: IntArray, target: Int): Int {
|
||||
// 轉化為查詢最左一個 target + 1
|
||||
val i = binarySearchInsertion(nums, target + 1)
|
||||
// j 指向最右一個 target ,i 指向首個大於 target 的元素
|
||||
val j = i - 1
|
||||
// 未找到 target ,返回 -1
|
||||
if (j == -1 || nums[j] != target) {
|
||||
return -1
|
||||
}
|
||||
// 找到 target ,返回索引 j
|
||||
return j
|
||||
}
|
||||
```
|
||||
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title="binary_search_edge.rb"
|
||||
[class]{}-[func]{binary_search_right_edge}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="binary_search_edge.zig"
|
||||
[class]{}-[func]{binarySearchRightEdge}
|
||||
```
|
||||
|
||||
??? pythontutor "視覺化執行"
|
||||
|
||||
<div style="height: 549px; width: 100%;"><iframe class="pythontutor-iframe" src="https://pythontutor.com/iframe-embed.html#code=def%20binary_search_insertion%28nums%3A%20list%5Bint%5D,%20target%3A%20int%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E6%8F%92%E5%85%A5%E7%82%B9%EF%BC%88%E5%AD%98%E5%9C%A8%E9%87%8D%E5%A4%8D%E5%85%83%E7%B4%A0%EF%BC%89%22%22%22%0A%20%20%20%20i,%20j%20%3D%200,%20len%28nums%29%20-%201%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%8F%8C%E9%97%AD%E5%8C%BA%E9%97%B4%20%5B0,%20n-1%5D%0A%20%20%20%20while%20i%20%3C%3D%20j%3A%0A%20%20%20%20%20%20%20%20m%20%3D%20%28i%20%2B%20j%29%20//%202%20%20%23%20%E8%AE%A1%E7%AE%97%E4%B8%AD%E7%82%B9%E7%B4%A2%E5%BC%95%20m%0A%20%20%20%20%20%20%20%20if%20nums%5Bm%5D%20%3C%20target%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20i%20%3D%20m%20%2B%201%20%20%23%20target%20%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bm%2B1,%20j%5D%20%E4%B8%AD%0A%20%20%20%20%20%20%20%20elif%20nums%5Bm%5D%20%3E%20target%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20j%20%3D%20m%20-%201%20%20%23%20target%20%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bi,%20m-1%5D%20%E4%B8%AD%0A%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20j%20%3D%20m%20-%201%20%20%23%20%E9%A6%96%E4%B8%AA%E5%B0%8F%E4%BA%8E%20target%20%E7%9A%84%E5%85%83%E7%B4%A0%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bi,%20m-1%5D%20%E4%B8%AD%0A%20%20%20%20%23%20%E8%BF%94%E5%9B%9E%E6%8F%92%E5%85%A5%E7%82%B9%20i%0A%20%20%20%20return%20i%0A%0Adef%20binary_search_right_edge%28nums%3A%20list%5Bint%5D,%20target%3A%20int%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E6%9C%80%E5%8F%B3%E4%B8%80%E4%B8%AA%20target%22%22%22%0A%20%20%20%20%23%20%E8%BD%AC%E5%8C%96%E4%B8%BA%E6%9F%A5%E6%89%BE%E6%9C%80%E5%B7%A6%E4%B8%80%E4%B8%AA%20target%20%2B%201%0A%20%20%20%20i%20%3D%20binary_search_insertion%28nums,%20target%20%2B%201%29%0A%20%20%20%20%23%20j%20%E6%8C%87%E5%90%91%E6%9C%80%E5%8F%B3%E4%B8%80%E4%B8%AA%20target%20%EF%BC%8Ci%20%E6%8C%87%E5%90%91%E9%A6%96%E4%B8%AA%E5%A4%A7%E4%BA%8E%20target%20%E7%9A%84%E5%85%83%E7%B4%A0%0A%20%20%20%20j%20%3D%20i%20-%201%0A%20%20%20%20%23%20%E6%9C%AA%E6%89%BE%E5%88%B0%20target%20%EF%BC%8C%E8%BF%94%E5%9B%9E%20-1%0A%20%20%20%20if%20j%20%3D%3D%20-1%20or%20nums%5Bj%5D%20!%3D%20target%3A%0A%20%20%20%20%20%20%20%20return%20-1%0A%20%20%20%20%23%20%E6%89%BE%E5%88%B0%20target%20%EF%BC%8C%E8%BF%94%E5%9B%9E%E7%B4%A2%E5%BC%95%20j%0A%20%20%20%20return%20j%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%8C%85%E5%90%AB%E9%87%8D%E5%A4%8D%E5%85%83%E7%B4%A0%E7%9A%84%E6%95%B0%E7%BB%84%0A%20%20%20%20nums%20%3D%20%5B1,%203,%206,%206,%206,%206,%206,%2010,%2012,%2015%5D%0A%20%20%20%20%23%20%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E5%B7%A6%E8%BE%B9%E7%95%8C%E5%92%8C%E5%8F%B3%E8%BE%B9%E7%95%8C%0A%20%20%20%20target%20%3D%206%0A%20%20%20%20index%20%3D%20binary_search_right_edge%28nums,%20target%29%0A%20%20%20%20print%28f%22%E6%9C%80%E5%8F%B3%E4%B8%80%E4%B8%AA%E5%85%83%E7%B4%A0%20%7Btarget%7D%20%E7%9A%84%E7%B4%A2%E5%BC%95%E4%B8%BA%20%7Bindex%7D%22%29&codeDivHeight=472&codeDivWidth=350&cumulative=false&curInstr=6&heapPrimitives=nevernest&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false"> </iframe></div>
|
||||
<div style="margin-top: 5px;"><a href="https://pythontutor.com/iframe-embed.html#code=def%20binary_search_insertion%28nums%3A%20list%5Bint%5D,%20target%3A%20int%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E6%8F%92%E5%85%A5%E7%82%B9%EF%BC%88%E5%AD%98%E5%9C%A8%E9%87%8D%E5%A4%8D%E5%85%83%E7%B4%A0%EF%BC%89%22%22%22%0A%20%20%20%20i,%20j%20%3D%200,%20len%28nums%29%20-%201%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%8F%8C%E9%97%AD%E5%8C%BA%E9%97%B4%20%5B0,%20n-1%5D%0A%20%20%20%20while%20i%20%3C%3D%20j%3A%0A%20%20%20%20%20%20%20%20m%20%3D%20%28i%20%2B%20j%29%20//%202%20%20%23%20%E8%AE%A1%E7%AE%97%E4%B8%AD%E7%82%B9%E7%B4%A2%E5%BC%95%20m%0A%20%20%20%20%20%20%20%20if%20nums%5Bm%5D%20%3C%20target%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20i%20%3D%20m%20%2B%201%20%20%23%20target%20%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bm%2B1,%20j%5D%20%E4%B8%AD%0A%20%20%20%20%20%20%20%20elif%20nums%5Bm%5D%20%3E%20target%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20j%20%3D%20m%20-%201%20%20%23%20target%20%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bi,%20m-1%5D%20%E4%B8%AD%0A%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20j%20%3D%20m%20-%201%20%20%23%20%E9%A6%96%E4%B8%AA%E5%B0%8F%E4%BA%8E%20target%20%E7%9A%84%E5%85%83%E7%B4%A0%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bi,%20m-1%5D%20%E4%B8%AD%0A%20%20%20%20%23%20%E8%BF%94%E5%9B%9E%E6%8F%92%E5%85%A5%E7%82%B9%20i%0A%20%20%20%20return%20i%0A%0Adef%20binary_search_right_edge%28nums%3A%20list%5Bint%5D,%20target%3A%20int%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E6%9C%80%E5%8F%B3%E4%B8%80%E4%B8%AA%20target%22%22%22%0A%20%20%20%20%23%20%E8%BD%AC%E5%8C%96%E4%B8%BA%E6%9F%A5%E6%89%BE%E6%9C%80%E5%B7%A6%E4%B8%80%E4%B8%AA%20target%20%2B%201%0A%20%20%20%20i%20%3D%20binary_search_insertion%28nums,%20target%20%2B%201%29%0A%20%20%20%20%23%20j%20%E6%8C%87%E5%90%91%E6%9C%80%E5%8F%B3%E4%B8%80%E4%B8%AA%20target%20%EF%BC%8Ci%20%E6%8C%87%E5%90%91%E9%A6%96%E4%B8%AA%E5%A4%A7%E4%BA%8E%20target%20%E7%9A%84%E5%85%83%E7%B4%A0%0A%20%20%20%20j%20%3D%20i%20-%201%0A%20%20%20%20%23%20%E6%9C%AA%E6%89%BE%E5%88%B0%20target%20%EF%BC%8C%E8%BF%94%E5%9B%9E%20-1%0A%20%20%20%20if%20j%20%3D%3D%20-1%20or%20nums%5Bj%5D%20!%3D%20target%3A%0A%20%20%20%20%20%20%20%20return%20-1%0A%20%20%20%20%23%20%E6%89%BE%E5%88%B0%20target%20%EF%BC%8C%E8%BF%94%E5%9B%9E%E7%B4%A2%E5%BC%95%20j%0A%20%20%20%20return%20j%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%8C%85%E5%90%AB%E9%87%8D%E5%A4%8D%E5%85%83%E7%B4%A0%E7%9A%84%E6%95%B0%E7%BB%84%0A%20%20%20%20nums%20%3D%20%5B1,%203,%206,%206,%206,%206,%206,%2010,%2012,%2015%5D%0A%20%20%20%20%23%20%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E5%B7%A6%E8%BE%B9%E7%95%8C%E5%92%8C%E5%8F%B3%E8%BE%B9%E7%95%8C%0A%20%20%20%20target%20%3D%206%0A%20%20%20%20index%20%3D%20binary_search_right_edge%28nums,%20target%29%0A%20%20%20%20print%28f%22%E6%9C%80%E5%8F%B3%E4%B8%80%E4%B8%AA%E5%85%83%E7%B4%A0%20%7Btarget%7D%20%E7%9A%84%E7%B4%A2%E5%BC%95%E4%B8%BA%20%7Bindex%7D%22%29&codeDivHeight=800&codeDivWidth=600&cumulative=false&curInstr=6&heapPrimitives=nevernest&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false" target="_blank" rel="noopener noreferrer">全螢幕觀看 ></a></div>
|
||||
|
||||
### 2. 轉化為查詢元素
|
||||
|
||||
我們知道,當陣列不包含 `target` 時,最終 $i$ 和 $j$ 會分別指向首個大於、小於 `target` 的元素。
|
||||
|
||||
因此,如圖 10-8 所示,我們可以構造一個陣列中不存在的元素,用於查詢左右邊界。
|
||||
|
||||
- 查詢最左一個 `target` :可以轉化為查詢 `target - 0.5` ,並返回指標 $i$ 。
|
||||
- 查詢最右一個 `target` :可以轉化為查詢 `target + 0.5` ,並返回指標 $j$ 。
|
||||
|
||||
{ class="animation-figure" }
|
||||
|
||||
<p align="center"> 圖 10-8 將查詢邊界轉化為查詢元素 </p>
|
||||
|
||||
程式碼在此省略,以下兩點值得注意。
|
||||
|
||||
- 給定陣列不包含小數,這意味著我們無須關心如何處理相等的情況。
|
||||
- 因為該方法引入了小數,所以需要將函式中的變數 `target` 改為浮點數型別(Python 無須改動)。
|
||||
@@ -0,0 +1,648 @@
|
||||
---
|
||||
comments: true
|
||||
---
|
||||
|
||||
# 10.2 二分搜尋插入點
|
||||
|
||||
二分搜尋不僅可用於搜尋目標元素,還可用於解決許多變種問題,比如搜尋目標元素的插入位置。
|
||||
|
||||
## 10.2.1 無重複元素的情況
|
||||
|
||||
!!! question
|
||||
|
||||
給定一個長度為 $n$ 的有序陣列 `nums` 和一個元素 `target` ,陣列不存在重複元素。現將 `target` 插入陣列 `nums` 中,並保持其有序性。若陣列中已存在元素 `target` ,則插入到其左方。請返回插入後 `target` 在陣列中的索引。示例如圖 10-4 所示。
|
||||
|
||||
{ class="animation-figure" }
|
||||
|
||||
<p align="center"> 圖 10-4 二分搜尋插入點示例資料 </p>
|
||||
|
||||
如果想複用上一節的二分搜尋程式碼,則需要回答以下兩個問題。
|
||||
|
||||
**問題一**:當陣列中包含 `target` 時,插入點的索引是否是該元素的索引?
|
||||
|
||||
題目要求將 `target` 插入到相等元素的左邊,這意味著新插入的 `target` 替換了原來 `target` 的位置。也就是說,**當陣列包含 `target` 時,插入點的索引就是該 `target` 的索引**。
|
||||
|
||||
**問題二**:當陣列中不存在 `target` 時,插入點是哪個元素的索引?
|
||||
|
||||
進一步思考二分搜尋過程:當 `nums[m] < target` 時 $i$ 移動,這意味著指標 $i$ 在向大於等於 `target` 的元素靠近。同理,指標 $j$ 始終在向小於等於 `target` 的元素靠近。
|
||||
|
||||
因此二分結束時一定有:$i$ 指向首個大於 `target` 的元素,$j$ 指向首個小於 `target` 的元素。**易得當陣列不包含 `target` 時,插入索引為 $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
|
||||
```
|
||||
|
||||
=== "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;
|
||||
}
|
||||
```
|
||||
|
||||
=== "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#"
|
||||
|
||||
```csharp title="binary_search_insertion.cs"
|
||||
/* 二分搜尋插入點(無重複元素) */
|
||||
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;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="binary_search_insertion.go"
|
||||
/* 二分搜尋插入點(無重複元素) */
|
||||
func binarySearchInsertionSimple(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
|
||||
return m
|
||||
}
|
||||
}
|
||||
// 未找到 target ,返回插入點 i
|
||||
return i
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="binary_search_insertion.swift"
|
||||
/* 二分搜尋插入點(無重複元素) */
|
||||
func binarySearchInsertionSimple(nums: [Int], target: Int) -> Int {
|
||||
// 初始化雙閉區間 [0, n-1]
|
||||
var i = nums.startIndex
|
||||
var j = nums.endIndex - 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 {
|
||||
return m // 找到 target ,返回插入點 m
|
||||
}
|
||||
}
|
||||
// 未找到 target ,返回插入點 i
|
||||
return i
|
||||
}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="binary_search_insertion.js"
|
||||
/* 二分搜尋插入點(無重複元素) */
|
||||
function binarySearchInsertionSimple(nums, target) {
|
||||
let i = 0,
|
||||
j = nums.length - 1; // 初始化雙閉區間 [0, n-1]
|
||||
while (i <= j) {
|
||||
const m = Math.floor(i + (j - i) / 2); // 計算中點索引 m, 使用 Math.floor() 向下取整
|
||||
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;
|
||||
}
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```typescript title="binary_search_insertion.ts"
|
||||
/* 二分搜尋插入點(無重複元素) */
|
||||
function binarySearchInsertionSimple(
|
||||
nums: Array<number>,
|
||||
target: number
|
||||
): number {
|
||||
let i = 0,
|
||||
j = nums.length - 1; // 初始化雙閉區間 [0, n-1]
|
||||
while (i <= j) {
|
||||
const m = Math.floor(i + (j - i) / 2); // 計算中點索引 m, 使用 Math.floor() 向下取整
|
||||
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;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="binary_search_insertion.dart"
|
||||
/* 二分搜尋插入點(無重複元素) */
|
||||
int binarySearchInsertionSimple(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 {
|
||||
return m; // 找到 target ,返回插入點 m
|
||||
}
|
||||
}
|
||||
// 未找到 target ,返回插入點 i
|
||||
return i;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="binary_search_insertion.rs"
|
||||
/* 二分搜尋插入點(無重複元素) */
|
||||
fn binary_search_insertion_simple(nums: &[i32], target: i32) -> i32 {
|
||||
let (mut i, mut j) = (0, 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 {
|
||||
return m;
|
||||
}
|
||||
}
|
||||
// 未找到 target ,返回插入點 i
|
||||
i
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="binary_search_insertion.c"
|
||||
/* 二分搜尋插入點(無重複元素) */
|
||||
int binarySearchInsertionSimple(int *nums, int numSize, int target) {
|
||||
int i = 0, j = numSize - 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;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Kotlin"
|
||||
|
||||
```kotlin title="binary_search_insertion.kt"
|
||||
/* 二分搜尋插入點(無重複元素) */
|
||||
fun binarySearchInsertionSimple(nums: IntArray, target: Int): Int {
|
||||
var i = 0
|
||||
var j = nums.size - 1 // 初始化雙閉區間 [0, n-1]
|
||||
while (i <= j) {
|
||||
val 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
|
||||
}
|
||||
```
|
||||
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title="binary_search_insertion.rb"
|
||||
[class]{}-[func]{binary_search_insertion_simple}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="binary_search_insertion.zig"
|
||||
[class]{}-[func]{binarySearchInsertionSimple}
|
||||
```
|
||||
|
||||
??? pythontutor "視覺化執行"
|
||||
|
||||
<div style="height: 549px; width: 100%;"><iframe class="pythontutor-iframe" src="https://pythontutor.com/iframe-embed.html#code=def%20binary_search_insertion_simple%28nums%3A%20list%5Bint%5D,%20target%3A%20int%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E6%8F%92%E5%85%A5%E7%82%B9%EF%BC%88%E6%97%A0%E9%87%8D%E5%A4%8D%E5%85%83%E7%B4%A0%EF%BC%89%22%22%22%0A%20%20%20%20i,%20j%20%3D%200,%20len%28nums%29%20-%201%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%8F%8C%E9%97%AD%E5%8C%BA%E9%97%B4%20%5B0,%20n-1%5D%0A%20%20%20%20while%20i%20%3C%3D%20j%3A%0A%20%20%20%20%20%20%20%20m%20%3D%20%28i%20%2B%20j%29%20//%202%20%20%23%20%E8%AE%A1%E7%AE%97%E4%B8%AD%E7%82%B9%E7%B4%A2%E5%BC%95%20m%0A%20%20%20%20%20%20%20%20if%20nums%5Bm%5D%20%3C%20target%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20i%20%3D%20m%20%2B%201%20%20%23%20target%20%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bm%2B1,%20j%5D%20%E4%B8%AD%0A%20%20%20%20%20%20%20%20elif%20nums%5Bm%5D%20%3E%20target%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20j%20%3D%20m%20-%201%20%20%23%20target%20%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bi,%20m-1%5D%20%E4%B8%AD%0A%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20return%20m%20%20%23%20%E6%89%BE%E5%88%B0%20target%20%EF%BC%8C%E8%BF%94%E5%9B%9E%E6%8F%92%E5%85%A5%E7%82%B9%20m%0A%20%20%20%20%23%20%E6%9C%AA%E6%89%BE%E5%88%B0%20target%20%EF%BC%8C%E8%BF%94%E5%9B%9E%E6%8F%92%E5%85%A5%E7%82%B9%20i%0A%20%20%20%20return%20i%0A%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E6%97%A0%E9%87%8D%E5%A4%8D%E5%85%83%E7%B4%A0%E7%9A%84%E6%95%B0%E7%BB%84%0A%20%20%20%20nums%20%3D%20%5B1,%203,%206,%208,%2012,%2015,%2023,%2026,%2031,%2035%5D%0A%20%20%20%20%23%20%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E6%8F%92%E5%85%A5%E7%82%B9%0A%20%20%20%20target%20%3D%206%0A%20%20%20%20index%20%3D%20binary_search_insertion_simple%28nums,%20target%29%0A%20%20%20%20print%28f%22%E5%85%83%E7%B4%A0%20%7Btarget%7D%20%E7%9A%84%E6%8F%92%E5%85%A5%E7%82%B9%E7%9A%84%E7%B4%A2%E5%BC%95%E4%B8%BA%20%7Bindex%7D%22%29&codeDivHeight=472&codeDivWidth=350&cumulative=false&curInstr=5&heapPrimitives=nevernest&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false"> </iframe></div>
|
||||
<div style="margin-top: 5px;"><a href="https://pythontutor.com/iframe-embed.html#code=def%20binary_search_insertion_simple%28nums%3A%20list%5Bint%5D,%20target%3A%20int%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E6%8F%92%E5%85%A5%E7%82%B9%EF%BC%88%E6%97%A0%E9%87%8D%E5%A4%8D%E5%85%83%E7%B4%A0%EF%BC%89%22%22%22%0A%20%20%20%20i,%20j%20%3D%200,%20len%28nums%29%20-%201%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%8F%8C%E9%97%AD%E5%8C%BA%E9%97%B4%20%5B0,%20n-1%5D%0A%20%20%20%20while%20i%20%3C%3D%20j%3A%0A%20%20%20%20%20%20%20%20m%20%3D%20%28i%20%2B%20j%29%20//%202%20%20%23%20%E8%AE%A1%E7%AE%97%E4%B8%AD%E7%82%B9%E7%B4%A2%E5%BC%95%20m%0A%20%20%20%20%20%20%20%20if%20nums%5Bm%5D%20%3C%20target%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20i%20%3D%20m%20%2B%201%20%20%23%20target%20%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bm%2B1,%20j%5D%20%E4%B8%AD%0A%20%20%20%20%20%20%20%20elif%20nums%5Bm%5D%20%3E%20target%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20j%20%3D%20m%20-%201%20%20%23%20target%20%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bi,%20m-1%5D%20%E4%B8%AD%0A%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20return%20m%20%20%23%20%E6%89%BE%E5%88%B0%20target%20%EF%BC%8C%E8%BF%94%E5%9B%9E%E6%8F%92%E5%85%A5%E7%82%B9%20m%0A%20%20%20%20%23%20%E6%9C%AA%E6%89%BE%E5%88%B0%20target%20%EF%BC%8C%E8%BF%94%E5%9B%9E%E6%8F%92%E5%85%A5%E7%82%B9%20i%0A%20%20%20%20return%20i%0A%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E6%97%A0%E9%87%8D%E5%A4%8D%E5%85%83%E7%B4%A0%E7%9A%84%E6%95%B0%E7%BB%84%0A%20%20%20%20nums%20%3D%20%5B1,%203,%206,%208,%2012,%2015,%2023,%2026,%2031,%2035%5D%0A%20%20%20%20%23%20%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E6%8F%92%E5%85%A5%E7%82%B9%0A%20%20%20%20target%20%3D%206%0A%20%20%20%20index%20%3D%20binary_search_insertion_simple%28nums,%20target%29%0A%20%20%20%20print%28f%22%E5%85%83%E7%B4%A0%20%7Btarget%7D%20%E7%9A%84%E6%8F%92%E5%85%A5%E7%82%B9%E7%9A%84%E7%B4%A2%E5%BC%95%E4%B8%BA%20%7Bindex%7D%22%29&codeDivHeight=800&codeDivWidth=600&cumulative=false&curInstr=5&heapPrimitives=nevernest&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false" target="_blank" rel="noopener noreferrer">全螢幕觀看 ></a></div>
|
||||
|
||||
## 10.2.2 存在重複元素的情況
|
||||
|
||||
!!! question
|
||||
|
||||
在上一題的基礎上,規定陣列可能包含重複元素,其餘不變。
|
||||
|
||||
假設陣列中存在多個 `target` ,則普通二分搜尋只能返回其中一個 `target` 的索引,**而無法確定該元素的左邊和右邊還有多少 `target`**。
|
||||
|
||||
題目要求將目標元素插入到最左邊,**所以我們需要查詢陣列中最左一個 `target` 的索引**。初步考慮透過圖 10-5 所示的步驟實現。
|
||||
|
||||
1. 執行二分搜尋,得到任意一個 `target` 的索引,記為 $k$ 。
|
||||
2. 從索引 $k$ 開始,向左進行線性走訪,當找到最左邊的 `target` 時返回。
|
||||
|
||||
{ class="animation-figure" }
|
||||
|
||||
<p align="center"> 圖 10-5 線性查詢重複元素的插入點 </p>
|
||||
|
||||
此方法雖然可用,但其包含線性查詢,因此時間複雜度為 $O(n)$ 。當陣列中存在很多重複的 `target` 時,該方法效率很低。
|
||||
|
||||
現考慮拓展二分搜尋程式碼。如圖 10-6 所示,整體流程保持不變,每輪先計算中點索引 $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>"
|
||||
{ class="animation-figure" }
|
||||
|
||||
=== "<2>"
|
||||
{ class="animation-figure" }
|
||||
|
||||
=== "<3>"
|
||||
{ class="animation-figure" }
|
||||
|
||||
=== "<4>"
|
||||
{ class="animation-figure" }
|
||||
|
||||
=== "<5>"
|
||||
{ class="animation-figure" }
|
||||
|
||||
=== "<6>"
|
||||
{ class="animation-figure" }
|
||||
|
||||
=== "<7>"
|
||||
{ class="animation-figure" }
|
||||
|
||||
=== "<8>"
|
||||
{ class="animation-figure" }
|
||||
|
||||
<p align="center"> 圖 10-6 二分搜尋重複元素的插入點的步驟 </p>
|
||||
|
||||
觀察以下程式碼,判斷分支 `nums[m] > target` 和 `nums[m] == target` 的操作相同,因此兩者可以合併。
|
||||
|
||||
即便如此,我們仍然可以將判斷條件保持展開,因為其邏輯更加清晰、可讀性更好。
|
||||
|
||||
=== "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
|
||||
```
|
||||
|
||||
=== "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;
|
||||
}
|
||||
```
|
||||
|
||||
=== "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#"
|
||||
|
||||
```csharp title="binary_search_insertion.cs"
|
||||
/* 二分搜尋插入點(存在重複元素) */
|
||||
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;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="binary_search_insertion.go"
|
||||
/* 二分搜尋插入點(存在重複元素) */
|
||||
func binarySearchInsertion(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
|
||||
}
|
||||
}
|
||||
// 返回插入點 i
|
||||
return i
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="binary_search_insertion.swift"
|
||||
/* 二分搜尋插入點(存在重複元素) */
|
||||
func binarySearchInsertion(nums: [Int], target: Int) -> Int {
|
||||
// 初始化雙閉區間 [0, n-1]
|
||||
var i = nums.startIndex
|
||||
var j = nums.endIndex - 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 {
|
||||
j = m - 1 // 首個小於 target 的元素在區間 [i, m-1] 中
|
||||
}
|
||||
}
|
||||
// 返回插入點 i
|
||||
return i
|
||||
}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="binary_search_insertion.js"
|
||||
/* 二分搜尋插入點(存在重複元素) */
|
||||
function binarySearchInsertion(nums, target) {
|
||||
let i = 0,
|
||||
j = nums.length - 1; // 初始化雙閉區間 [0, n-1]
|
||||
while (i <= j) {
|
||||
const m = Math.floor(i + (j - i) / 2); // 計算中點索引 m, 使用 Math.floor() 向下取整
|
||||
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;
|
||||
}
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```typescript title="binary_search_insertion.ts"
|
||||
/* 二分搜尋插入點(存在重複元素) */
|
||||
function binarySearchInsertion(nums: Array<number>, target: number): number {
|
||||
let i = 0,
|
||||
j = nums.length - 1; // 初始化雙閉區間 [0, n-1]
|
||||
while (i <= j) {
|
||||
const m = Math.floor(i + (j - i) / 2); // 計算中點索引 m, 使用 Math.floor() 向下取整
|
||||
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;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="binary_search_insertion.dart"
|
||||
/* 二分搜尋插入點(存在重複元素) */
|
||||
int binarySearchInsertion(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] 中
|
||||
}
|
||||
}
|
||||
// 返回插入點 i
|
||||
return i;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="binary_search_insertion.rs"
|
||||
/* 二分搜尋插入點(存在重複元素) */
|
||||
pub fn binary_search_insertion(nums: &[i32], target: i32) -> i32 {
|
||||
let (mut i, mut j) = (0, 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] 中
|
||||
}
|
||||
}
|
||||
// 返回插入點 i
|
||||
i
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="binary_search_insertion.c"
|
||||
/* 二分搜尋插入點(存在重複元素) */
|
||||
int binarySearchInsertion(int *nums, int numSize, int target) {
|
||||
int i = 0, j = numSize - 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;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Kotlin"
|
||||
|
||||
```kotlin title="binary_search_insertion.kt"
|
||||
/* 二分搜尋插入點(存在重複元素) */
|
||||
fun binarySearchInsertion(nums: IntArray, target: Int): Int {
|
||||
var i = 0
|
||||
var j = nums.size - 1 // 初始化雙閉區間 [0, n-1]
|
||||
while (i <= j) {
|
||||
val 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
|
||||
}
|
||||
```
|
||||
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title="binary_search_insertion.rb"
|
||||
[class]{}-[func]{binary_search_insertion}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="binary_search_insertion.zig"
|
||||
[class]{}-[func]{binarySearchInsertion}
|
||||
```
|
||||
|
||||
??? pythontutor "視覺化執行"
|
||||
|
||||
<div style="height: 549px; width: 100%;"><iframe class="pythontutor-iframe" src="https://pythontutor.com/iframe-embed.html#code=def%20binary_search_insertion%28nums%3A%20list%5Bint%5D,%20target%3A%20int%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E6%8F%92%E5%85%A5%E7%82%B9%EF%BC%88%E5%AD%98%E5%9C%A8%E9%87%8D%E5%A4%8D%E5%85%83%E7%B4%A0%EF%BC%89%22%22%22%0A%20%20%20%20i,%20j%20%3D%200,%20len%28nums%29%20-%201%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%8F%8C%E9%97%AD%E5%8C%BA%E9%97%B4%20%5B0,%20n-1%5D%0A%20%20%20%20while%20i%20%3C%3D%20j%3A%0A%20%20%20%20%20%20%20%20m%20%3D%20%28i%20%2B%20j%29%20//%202%20%20%23%20%E8%AE%A1%E7%AE%97%E4%B8%AD%E7%82%B9%E7%B4%A2%E5%BC%95%20m%0A%20%20%20%20%20%20%20%20if%20nums%5Bm%5D%20%3C%20target%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20i%20%3D%20m%20%2B%201%20%20%23%20target%20%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bm%2B1,%20j%5D%20%E4%B8%AD%0A%20%20%20%20%20%20%20%20elif%20nums%5Bm%5D%20%3E%20target%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20j%20%3D%20m%20-%201%20%20%23%20target%20%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bi,%20m-1%5D%20%E4%B8%AD%0A%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20j%20%3D%20m%20-%201%20%20%23%20%E9%A6%96%E4%B8%AA%E5%B0%8F%E4%BA%8E%20target%20%E7%9A%84%E5%85%83%E7%B4%A0%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bi,%20m-1%5D%20%E4%B8%AD%0A%20%20%20%20%23%20%E8%BF%94%E5%9B%9E%E6%8F%92%E5%85%A5%E7%82%B9%20i%0A%20%20%20%20return%20i%0A%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%8C%85%E5%90%AB%E9%87%8D%E5%A4%8D%E5%85%83%E7%B4%A0%E7%9A%84%E6%95%B0%E7%BB%84%0A%20%20%20%20nums%20%3D%20%5B1,%203,%206,%206,%206,%206,%206,%2010,%2012,%2015%5D%0A%20%20%20%20%23%20%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E6%8F%92%E5%85%A5%E7%82%B9%0A%20%20%20%20target%20%3D%206%0A%20%20%20%20index%20%3D%20binary_search_insertion%28nums,%20target%29%0A%20%20%20%20print%28f%22%E5%85%83%E7%B4%A0%20%7Btarget%7D%20%E7%9A%84%E6%8F%92%E5%85%A5%E7%82%B9%E7%9A%84%E7%B4%A2%E5%BC%95%E4%B8%BA%20%7Bindex%7D%22%29&codeDivHeight=472&codeDivWidth=350&cumulative=false&curInstr=5&heapPrimitives=nevernest&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false"> </iframe></div>
|
||||
<div style="margin-top: 5px;"><a href="https://pythontutor.com/iframe-embed.html#code=def%20binary_search_insertion%28nums%3A%20list%5Bint%5D,%20target%3A%20int%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E6%8F%92%E5%85%A5%E7%82%B9%EF%BC%88%E5%AD%98%E5%9C%A8%E9%87%8D%E5%A4%8D%E5%85%83%E7%B4%A0%EF%BC%89%22%22%22%0A%20%20%20%20i,%20j%20%3D%200,%20len%28nums%29%20-%201%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%8F%8C%E9%97%AD%E5%8C%BA%E9%97%B4%20%5B0,%20n-1%5D%0A%20%20%20%20while%20i%20%3C%3D%20j%3A%0A%20%20%20%20%20%20%20%20m%20%3D%20%28i%20%2B%20j%29%20//%202%20%20%23%20%E8%AE%A1%E7%AE%97%E4%B8%AD%E7%82%B9%E7%B4%A2%E5%BC%95%20m%0A%20%20%20%20%20%20%20%20if%20nums%5Bm%5D%20%3C%20target%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20i%20%3D%20m%20%2B%201%20%20%23%20target%20%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bm%2B1,%20j%5D%20%E4%B8%AD%0A%20%20%20%20%20%20%20%20elif%20nums%5Bm%5D%20%3E%20target%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20j%20%3D%20m%20-%201%20%20%23%20target%20%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bi,%20m-1%5D%20%E4%B8%AD%0A%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20j%20%3D%20m%20-%201%20%20%23%20%E9%A6%96%E4%B8%AA%E5%B0%8F%E4%BA%8E%20target%20%E7%9A%84%E5%85%83%E7%B4%A0%E5%9C%A8%E5%8C%BA%E9%97%B4%20%5Bi,%20m-1%5D%20%E4%B8%AD%0A%20%20%20%20%23%20%E8%BF%94%E5%9B%9E%E6%8F%92%E5%85%A5%E7%82%B9%20i%0A%20%20%20%20return%20i%0A%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%8C%85%E5%90%AB%E9%87%8D%E5%A4%8D%E5%85%83%E7%B4%A0%E7%9A%84%E6%95%B0%E7%BB%84%0A%20%20%20%20nums%20%3D%20%5B1,%203,%206,%206,%206,%206,%206,%2010,%2012,%2015%5D%0A%20%20%20%20%23%20%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E6%8F%92%E5%85%A5%E7%82%B9%0A%20%20%20%20target%20%3D%206%0A%20%20%20%20index%20%3D%20binary_search_insertion%28nums,%20target%29%0A%20%20%20%20print%28f%22%E5%85%83%E7%B4%A0%20%7Btarget%7D%20%E7%9A%84%E6%8F%92%E5%85%A5%E7%82%B9%E7%9A%84%E7%B4%A2%E5%BC%95%E4%B8%BA%20%7Bindex%7D%22%29&codeDivHeight=800&codeDivWidth=600&cumulative=false&curInstr=5&heapPrimitives=nevernest&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false" target="_blank" rel="noopener noreferrer">全螢幕觀看 ></a></div>
|
||||
|
||||
!!! tip
|
||||
|
||||
本節的程式碼都是“雙閉區間”寫法。有興趣的讀者可以自行實現“左閉右開”寫法。
|
||||
|
||||
總的來看,二分搜尋無非就是給指標 $i$ 和 $j$ 分別設定搜尋目標,目標可能是一個具體的元素(例如 `target` ),也可能是一個元素範圍(例如小於 `target` 的元素)。
|
||||
|
||||
在不斷的迴圈二分中,指標 $i$ 和 $j$ 都逐漸逼近預先設定的目標。最終,它們或是成功找到答案,或是越過邊界後停止。
|
||||
@@ -0,0 +1,23 @@
|
||||
---
|
||||
comments: true
|
||||
icon: material/text-search
|
||||
---
|
||||
|
||||
# 第 10 章 搜尋
|
||||
|
||||
{ class="cover-image" }
|
||||
|
||||
!!! abstract
|
||||
|
||||
搜尋是一場未知的冒險,我們或許需要走遍神秘空間的每個角落,又或許可以快速鎖定目標。
|
||||
|
||||
在這場尋覓之旅中,每一次探索都可能得到一個未曾料想的答案。
|
||||
|
||||
## Chapter Contents
|
||||
|
||||
- [10.1 二分搜尋](https://www.hello-algo.com/en/chapter_searching/binary_search/)
|
||||
- [10.2 二分搜尋插入點](https://www.hello-algo.com/en/chapter_searching/binary_search_insertion/)
|
||||
- [10.3 二分搜尋邊界](https://www.hello-algo.com/en/chapter_searching/binary_search_edge/)
|
||||
- [10.4 雜湊最佳化策略](https://www.hello-algo.com/en/chapter_searching/replace_linear_by_hashing/)
|
||||
- [10.5 重識搜尋演算法](https://www.hello-algo.com/en/chapter_searching/searching_algorithm_revisited/)
|
||||
- [10.6 小結](https://www.hello-algo.com/en/chapter_searching/summary/)
|
||||
+565
@@ -0,0 +1,565 @@
|
||||
---
|
||||
comments: true
|
||||
---
|
||||
|
||||
# 10.4 雜湊最佳化策略
|
||||
|
||||
在演算法題中,**我們常透過將線性查詢替換為雜湊查詢來降低演算法的時間複雜度**。我們藉助一個演算法題來加深理解。
|
||||
|
||||
!!! question
|
||||
|
||||
給定一個整數陣列 `nums` 和一個目標元素 `target` ,請在陣列中搜索“和”為 `target` 的兩個元素,並返回它們的陣列索引。返回任意一個解即可。
|
||||
|
||||
## 10.4.1 線性查詢:以時間換空間
|
||||
|
||||
考慮直接走訪所有可能的組合。如圖 10-9 所示,我們開啟一個兩層迴圈,在每輪中判斷兩個整數的和是否為 `target` ,若是,則返回它們的索引。
|
||||
|
||||
{ class="animation-figure" }
|
||||
|
||||
<p align="center"> 圖 10-9 線性查詢求解兩數之和 </p>
|
||||
|
||||
程式碼如下所示:
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="two_sum.py"
|
||||
def two_sum_brute_force(nums: list[int], target: int) -> list[int]:
|
||||
"""方法一:暴力列舉"""
|
||||
# 兩層迴圈,時間複雜度為 O(n^2)
|
||||
for i in range(len(nums) - 1):
|
||||
for j in range(i + 1, len(nums)):
|
||||
if nums[i] + nums[j] == target:
|
||||
return [i, j]
|
||||
return []
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="two_sum.cpp"
|
||||
/* 方法一:暴力列舉 */
|
||||
vector<int> twoSumBruteForce(vector<int> &nums, int target) {
|
||||
int size = nums.size();
|
||||
// 兩層迴圈,時間複雜度為 O(n^2)
|
||||
for (int i = 0; i < size - 1; i++) {
|
||||
for (int j = i + 1; j < size; j++) {
|
||||
if (nums[i] + nums[j] == target)
|
||||
return {i, j};
|
||||
}
|
||||
}
|
||||
return {};
|
||||
}
|
||||
```
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="two_sum.java"
|
||||
/* 方法一:暴力列舉 */
|
||||
int[] twoSumBruteForce(int[] nums, int target) {
|
||||
int size = nums.length;
|
||||
// 兩層迴圈,時間複雜度為 O(n^2)
|
||||
for (int i = 0; i < size - 1; i++) {
|
||||
for (int j = i + 1; j < size; j++) {
|
||||
if (nums[i] + nums[j] == target)
|
||||
return new int[] { i, j };
|
||||
}
|
||||
}
|
||||
return new int[0];
|
||||
}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="two_sum.cs"
|
||||
/* 方法一:暴力列舉 */
|
||||
int[] TwoSumBruteForce(int[] nums, int target) {
|
||||
int size = nums.Length;
|
||||
// 兩層迴圈,時間複雜度為 O(n^2)
|
||||
for (int i = 0; i < size - 1; i++) {
|
||||
for (int j = i + 1; j < size; j++) {
|
||||
if (nums[i] + nums[j] == target)
|
||||
return [i, j];
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="two_sum.go"
|
||||
/* 方法一:暴力列舉 */
|
||||
func twoSumBruteForce(nums []int, target int) []int {
|
||||
size := len(nums)
|
||||
// 兩層迴圈,時間複雜度為 O(n^2)
|
||||
for i := 0; i < size-1; i++ {
|
||||
for j := i + 1; i < size; j++ {
|
||||
if nums[i]+nums[j] == target {
|
||||
return []int{i, j}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="two_sum.swift"
|
||||
/* 方法一:暴力列舉 */
|
||||
func twoSumBruteForce(nums: [Int], target: Int) -> [Int] {
|
||||
// 兩層迴圈,時間複雜度為 O(n^2)
|
||||
for i in nums.indices.dropLast() {
|
||||
for j in nums.indices.dropFirst(i + 1) {
|
||||
if nums[i] + nums[j] == target {
|
||||
return [i, j]
|
||||
}
|
||||
}
|
||||
}
|
||||
return [0]
|
||||
}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="two_sum.js"
|
||||
/* 方法一:暴力列舉 */
|
||||
function twoSumBruteForce(nums, target) {
|
||||
const n = nums.length;
|
||||
// 兩層迴圈,時間複雜度為 O(n^2)
|
||||
for (let i = 0; i < n; i++) {
|
||||
for (let j = i + 1; j < n; j++) {
|
||||
if (nums[i] + nums[j] === target) {
|
||||
return [i, j];
|
||||
}
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```typescript title="two_sum.ts"
|
||||
/* 方法一:暴力列舉 */
|
||||
function twoSumBruteForce(nums: number[], target: number): number[] {
|
||||
const n = nums.length;
|
||||
// 兩層迴圈,時間複雜度為 O(n^2)
|
||||
for (let i = 0; i < n; i++) {
|
||||
for (let j = i + 1; j < n; j++) {
|
||||
if (nums[i] + nums[j] === target) {
|
||||
return [i, j];
|
||||
}
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="two_sum.dart"
|
||||
/* 方法一: 暴力列舉 */
|
||||
List<int> twoSumBruteForce(List<int> nums, int target) {
|
||||
int size = nums.length;
|
||||
// 兩層迴圈,時間複雜度為 O(n^2)
|
||||
for (var i = 0; i < size - 1; i++) {
|
||||
for (var j = i + 1; j < size; j++) {
|
||||
if (nums[i] + nums[j] == target) return [i, j];
|
||||
}
|
||||
}
|
||||
return [0];
|
||||
}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="two_sum.rs"
|
||||
/* 方法一:暴力列舉 */
|
||||
pub fn two_sum_brute_force(nums: &Vec<i32>, target: i32) -> Option<Vec<i32>> {
|
||||
let size = nums.len();
|
||||
// 兩層迴圈,時間複雜度為 O(n^2)
|
||||
for i in 0..size - 1 {
|
||||
for j in i + 1..size {
|
||||
if nums[i] + nums[j] == target {
|
||||
return Some(vec![i as i32, j as i32]);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="two_sum.c"
|
||||
/* 方法一:暴力列舉 */
|
||||
int *twoSumBruteForce(int *nums, int numsSize, int target, int *returnSize) {
|
||||
for (int i = 0; i < numsSize; ++i) {
|
||||
for (int j = i + 1; j < numsSize; ++j) {
|
||||
if (nums[i] + nums[j] == target) {
|
||||
int *res = malloc(sizeof(int) * 2);
|
||||
res[0] = i, res[1] = j;
|
||||
*returnSize = 2;
|
||||
return res;
|
||||
}
|
||||
}
|
||||
}
|
||||
*returnSize = 0;
|
||||
return NULL;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Kotlin"
|
||||
|
||||
```kotlin title="two_sum.kt"
|
||||
/* 方法一:暴力列舉 */
|
||||
fun twoSumBruteForce(nums: IntArray, target: Int): IntArray {
|
||||
val size = nums.size
|
||||
// 兩層迴圈,時間複雜度為 O(n^2)
|
||||
for (i in 0..<size - 1) {
|
||||
for (j in i + 1..<size) {
|
||||
if (nums[i] + nums[j] == target) return intArrayOf(i, j)
|
||||
}
|
||||
}
|
||||
return IntArray(0)
|
||||
}
|
||||
```
|
||||
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title="two_sum.rb"
|
||||
[class]{}-[func]{two_sum_brute_force}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="two_sum.zig"
|
||||
// 方法一:暴力列舉
|
||||
fn twoSumBruteForce(nums: []i32, target: i32) ?[2]i32 {
|
||||
var size: usize = nums.len;
|
||||
var i: usize = 0;
|
||||
// 兩層迴圈,時間複雜度為 O(n^2)
|
||||
while (i < size - 1) : (i += 1) {
|
||||
var j = i + 1;
|
||||
while (j < size) : (j += 1) {
|
||||
if (nums[i] + nums[j] == target) {
|
||||
return [_]i32{@intCast(i), @intCast(j)};
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
```
|
||||
|
||||
??? pythontutor "視覺化執行"
|
||||
|
||||
<div style="height: 441px; width: 100%;"><iframe class="pythontutor-iframe" src="https://pythontutor.com/iframe-embed.html#code=def%20two_sum_brute_force%28nums%3A%20list%5Bint%5D,%20target%3A%20int%29%20-%3E%20list%5Bint%5D%3A%0A%20%20%20%20%22%22%22%E6%96%B9%E6%B3%95%E4%B8%80%EF%BC%9A%E6%9A%B4%E5%8A%9B%E6%9E%9A%E4%B8%BE%22%22%22%0A%20%20%20%20%23%20%E4%B8%A4%E5%B1%82%E5%BE%AA%E7%8E%AF%EF%BC%8C%E6%97%B6%E9%97%B4%E5%A4%8D%E6%9D%82%E5%BA%A6%E4%B8%BA%20O%28n%5E2%29%0A%20%20%20%20for%20i%20in%20range%28len%28nums%29%20-%201%29%3A%0A%20%20%20%20%20%20%20%20for%20j%20in%20range%28i%20%2B%201,%20len%28nums%29%29%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20if%20nums%5Bi%5D%20%2B%20nums%5Bj%5D%20%3D%3D%20target%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20return%20%5Bi,%20j%5D%0A%20%20%20%20return%20%5B%5D%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20nums%20%3D%20%5B2,%207,%2011,%2015%5D%0A%20%20%20%20target%20%3D%2013%0A%20%20%20%20res%20%3D%20two_sum_brute_force%28nums,%20target%29&codeDivHeight=472&codeDivWidth=350&cumulative=false&curInstr=5&heapPrimitives=nevernest&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false"> </iframe></div>
|
||||
<div style="margin-top: 5px;"><a href="https://pythontutor.com/iframe-embed.html#code=def%20two_sum_brute_force%28nums%3A%20list%5Bint%5D,%20target%3A%20int%29%20-%3E%20list%5Bint%5D%3A%0A%20%20%20%20%22%22%22%E6%96%B9%E6%B3%95%E4%B8%80%EF%BC%9A%E6%9A%B4%E5%8A%9B%E6%9E%9A%E4%B8%BE%22%22%22%0A%20%20%20%20%23%20%E4%B8%A4%E5%B1%82%E5%BE%AA%E7%8E%AF%EF%BC%8C%E6%97%B6%E9%97%B4%E5%A4%8D%E6%9D%82%E5%BA%A6%E4%B8%BA%20O%28n%5E2%29%0A%20%20%20%20for%20i%20in%20range%28len%28nums%29%20-%201%29%3A%0A%20%20%20%20%20%20%20%20for%20j%20in%20range%28i%20%2B%201,%20len%28nums%29%29%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20if%20nums%5Bi%5D%20%2B%20nums%5Bj%5D%20%3D%3D%20target%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20return%20%5Bi,%20j%5D%0A%20%20%20%20return%20%5B%5D%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20nums%20%3D%20%5B2,%207,%2011,%2015%5D%0A%20%20%20%20target%20%3D%2013%0A%20%20%20%20res%20%3D%20two_sum_brute_force%28nums,%20target%29&codeDivHeight=800&codeDivWidth=600&cumulative=false&curInstr=5&heapPrimitives=nevernest&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false" target="_blank" rel="noopener noreferrer">全螢幕觀看 ></a></div>
|
||||
|
||||
此方法的時間複雜度為 $O(n^2)$ ,空間複雜度為 $O(1)$ ,在大資料量下非常耗時。
|
||||
|
||||
## 10.4.2 雜湊查詢:以空間換時間
|
||||
|
||||
考慮藉助一個雜湊表,鍵值對分別為陣列元素和元素索引。迴圈走訪陣列,每輪執行圖 10-10 所示的步驟。
|
||||
|
||||
1. 判斷數字 `target - nums[i]` 是否在雜湊表中,若是,則直接返回這兩個元素的索引。
|
||||
2. 將鍵值對 `nums[i]` 和索引 `i` 新增進雜湊表。
|
||||
|
||||
=== "<1>"
|
||||
{ class="animation-figure" }
|
||||
|
||||
=== "<2>"
|
||||
{ class="animation-figure" }
|
||||
|
||||
=== "<3>"
|
||||
{ class="animation-figure" }
|
||||
|
||||
<p align="center"> 圖 10-10 輔助雜湊表求解兩數之和 </p>
|
||||
|
||||
實現程式碼如下所示,僅需單層迴圈即可:
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="two_sum.py"
|
||||
def two_sum_hash_table(nums: list[int], target: int) -> list[int]:
|
||||
"""方法二:輔助雜湊表"""
|
||||
# 輔助雜湊表,空間複雜度為 O(n)
|
||||
dic = {}
|
||||
# 單層迴圈,時間複雜度為 O(n)
|
||||
for i in range(len(nums)):
|
||||
if target - nums[i] in dic:
|
||||
return [dic[target - nums[i]], i]
|
||||
dic[nums[i]] = i
|
||||
return []
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="two_sum.cpp"
|
||||
/* 方法二:輔助雜湊表 */
|
||||
vector<int> twoSumHashTable(vector<int> &nums, int target) {
|
||||
int size = nums.size();
|
||||
// 輔助雜湊表,空間複雜度為 O(n)
|
||||
unordered_map<int, int> dic;
|
||||
// 單層迴圈,時間複雜度為 O(n)
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (dic.find(target - nums[i]) != dic.end()) {
|
||||
return {dic[target - nums[i]], i};
|
||||
}
|
||||
dic.emplace(nums[i], i);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
```
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="two_sum.java"
|
||||
/* 方法二:輔助雜湊表 */
|
||||
int[] twoSumHashTable(int[] nums, int target) {
|
||||
int size = nums.length;
|
||||
// 輔助雜湊表,空間複雜度為 O(n)
|
||||
Map<Integer, Integer> dic = new HashMap<>();
|
||||
// 單層迴圈,時間複雜度為 O(n)
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (dic.containsKey(target - nums[i])) {
|
||||
return new int[] { dic.get(target - nums[i]), i };
|
||||
}
|
||||
dic.put(nums[i], i);
|
||||
}
|
||||
return new int[0];
|
||||
}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="two_sum.cs"
|
||||
/* 方法二:輔助雜湊表 */
|
||||
int[] TwoSumHashTable(int[] nums, int target) {
|
||||
int size = nums.Length;
|
||||
// 輔助雜湊表,空間複雜度為 O(n)
|
||||
Dictionary<int, int> dic = [];
|
||||
// 單層迴圈,時間複雜度為 O(n)
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (dic.ContainsKey(target - nums[i])) {
|
||||
return [dic[target - nums[i]], i];
|
||||
}
|
||||
dic.Add(nums[i], i);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="two_sum.go"
|
||||
/* 方法二:輔助雜湊表 */
|
||||
func twoSumHashTable(nums []int, target int) []int {
|
||||
// 輔助雜湊表,空間複雜度為 O(n)
|
||||
hashTable := map[int]int{}
|
||||
// 單層迴圈,時間複雜度為 O(n)
|
||||
for idx, val := range nums {
|
||||
if preIdx, ok := hashTable[target-val]; ok {
|
||||
return []int{preIdx, idx}
|
||||
}
|
||||
hashTable[val] = idx
|
||||
}
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="two_sum.swift"
|
||||
/* 方法二:輔助雜湊表 */
|
||||
func twoSumHashTable(nums: [Int], target: Int) -> [Int] {
|
||||
// 輔助雜湊表,空間複雜度為 O(n)
|
||||
var dic: [Int: Int] = [:]
|
||||
// 單層迴圈,時間複雜度為 O(n)
|
||||
for i in nums.indices {
|
||||
if let j = dic[target - nums[i]] {
|
||||
return [j, i]
|
||||
}
|
||||
dic[nums[i]] = i
|
||||
}
|
||||
return [0]
|
||||
}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="two_sum.js"
|
||||
/* 方法二:輔助雜湊表 */
|
||||
function twoSumHashTable(nums, target) {
|
||||
// 輔助雜湊表,空間複雜度為 O(n)
|
||||
let m = {};
|
||||
// 單層迴圈,時間複雜度為 O(n)
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
if (m[target - nums[i]] !== undefined) {
|
||||
return [m[target - nums[i]], i];
|
||||
} else {
|
||||
m[nums[i]] = i;
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```typescript title="two_sum.ts"
|
||||
/* 方法二:輔助雜湊表 */
|
||||
function twoSumHashTable(nums: number[], target: number): number[] {
|
||||
// 輔助雜湊表,空間複雜度為 O(n)
|
||||
let m: Map<number, number> = new Map();
|
||||
// 單層迴圈,時間複雜度為 O(n)
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
let index = m.get(target - nums[i]);
|
||||
if (index !== undefined) {
|
||||
return [index, i];
|
||||
} else {
|
||||
m.set(nums[i], i);
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="two_sum.dart"
|
||||
/* 方法二: 輔助雜湊表 */
|
||||
List<int> twoSumHashTable(List<int> nums, int target) {
|
||||
int size = nums.length;
|
||||
// 輔助雜湊表,空間複雜度為 O(n)
|
||||
Map<int, int> dic = HashMap();
|
||||
// 單層迴圈,時間複雜度為 O(n)
|
||||
for (var i = 0; i < size; i++) {
|
||||
if (dic.containsKey(target - nums[i])) {
|
||||
return [dic[target - nums[i]]!, i];
|
||||
}
|
||||
dic.putIfAbsent(nums[i], () => i);
|
||||
}
|
||||
return [0];
|
||||
}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="two_sum.rs"
|
||||
/* 方法二:輔助雜湊表 */
|
||||
pub fn two_sum_hash_table(nums: &Vec<i32>, target: i32) -> Option<Vec<i32>> {
|
||||
// 輔助雜湊表,空間複雜度為 O(n)
|
||||
let mut dic = HashMap::new();
|
||||
// 單層迴圈,時間複雜度為 O(n)
|
||||
for (i, num) in nums.iter().enumerate() {
|
||||
match dic.get(&(target - num)) {
|
||||
Some(v) => return Some(vec![*v as i32, i as i32]),
|
||||
None => dic.insert(num, i as i32),
|
||||
};
|
||||
}
|
||||
None
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="two_sum.c"
|
||||
/* 雜湊表 */
|
||||
typedef struct {
|
||||
int key;
|
||||
int val;
|
||||
UT_hash_handle hh; // 基於 uthash.h 實現
|
||||
} HashTable;
|
||||
|
||||
/* 雜湊表查詢 */
|
||||
HashTable *find(HashTable *h, int key) {
|
||||
HashTable *tmp;
|
||||
HASH_FIND_INT(h, &key, tmp);
|
||||
return tmp;
|
||||
}
|
||||
|
||||
/* 雜湊表元素插入 */
|
||||
void insert(HashTable *h, int key, int val) {
|
||||
HashTable *t = find(h, key);
|
||||
if (t == NULL) {
|
||||
HashTable *tmp = malloc(sizeof(HashTable));
|
||||
tmp->key = key, tmp->val = val;
|
||||
HASH_ADD_INT(h, key, tmp);
|
||||
} else {
|
||||
t->val = val;
|
||||
}
|
||||
}
|
||||
|
||||
/* 方法二:輔助雜湊表 */
|
||||
int *twoSumHashTable(int *nums, int numsSize, int target, int *returnSize) {
|
||||
HashTable *hashtable = NULL;
|
||||
for (int i = 0; i < numsSize; i++) {
|
||||
HashTable *t = find(hashtable, target - nums[i]);
|
||||
if (t != NULL) {
|
||||
int *res = malloc(sizeof(int) * 2);
|
||||
res[0] = t->val, res[1] = i;
|
||||
*returnSize = 2;
|
||||
return res;
|
||||
}
|
||||
insert(hashtable, nums[i], i);
|
||||
}
|
||||
*returnSize = 0;
|
||||
return NULL;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Kotlin"
|
||||
|
||||
```kotlin title="two_sum.kt"
|
||||
/* 方法二:輔助雜湊表 */
|
||||
fun twoSumHashTable(nums: IntArray, target: Int): IntArray {
|
||||
val size = nums.size
|
||||
// 輔助雜湊表,空間複雜度為 O(n)
|
||||
val dic = HashMap<Int, Int>()
|
||||
// 單層迴圈,時間複雜度為 O(n)
|
||||
for (i in 0..<size) {
|
||||
if (dic.containsKey(target - nums[i])) {
|
||||
return intArrayOf(dic[target - nums[i]]!!, i)
|
||||
}
|
||||
dic[nums[i]] = i
|
||||
}
|
||||
return IntArray(0)
|
||||
}
|
||||
```
|
||||
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title="two_sum.rb"
|
||||
[class]{}-[func]{two_sum_hash_table}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="two_sum.zig"
|
||||
// 方法二:輔助雜湊表
|
||||
fn twoSumHashTable(nums: []i32, target: i32) !?[2]i32 {
|
||||
var size: usize = nums.len;
|
||||
// 輔助雜湊表,空間複雜度為 O(n)
|
||||
var dic = std.AutoHashMap(i32, i32).init(std.heap.page_allocator);
|
||||
defer dic.deinit();
|
||||
var i: usize = 0;
|
||||
// 單層迴圈,時間複雜度為 O(n)
|
||||
while (i < size) : (i += 1) {
|
||||
if (dic.contains(target - nums[i])) {
|
||||
return [_]i32{dic.get(target - nums[i]).?, @intCast(i)};
|
||||
}
|
||||
try dic.put(nums[i], @intCast(i));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
```
|
||||
|
||||
??? pythontutor "視覺化執行"
|
||||
|
||||
<div style="height: 477px; width: 100%;"><iframe class="pythontutor-iframe" src="https://pythontutor.com/iframe-embed.html#code=def%20two_sum_hash_table%28nums%3A%20list%5Bint%5D,%20target%3A%20int%29%20-%3E%20list%5Bint%5D%3A%0A%20%20%20%20%22%22%22%E6%96%B9%E6%B3%95%E4%BA%8C%EF%BC%9A%E8%BE%85%E5%8A%A9%E5%93%88%E5%B8%8C%E8%A1%A8%22%22%22%0A%20%20%20%20%23%20%E8%BE%85%E5%8A%A9%E5%93%88%E5%B8%8C%E8%A1%A8%EF%BC%8C%E7%A9%BA%E9%97%B4%E5%A4%8D%E6%9D%82%E5%BA%A6%E4%B8%BA%20O%28n%29%0A%20%20%20%20dic%20%3D%20%7B%7D%0A%20%20%20%20%23%20%E5%8D%95%E5%B1%82%E5%BE%AA%E7%8E%AF%EF%BC%8C%E6%97%B6%E9%97%B4%E5%A4%8D%E6%9D%82%E5%BA%A6%E4%B8%BA%20O%28n%29%0A%20%20%20%20for%20i%20in%20range%28len%28nums%29%29%3A%0A%20%20%20%20%20%20%20%20if%20target%20-%20nums%5Bi%5D%20in%20dic%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20return%20%5Bdic%5Btarget%20-%20nums%5Bi%5D%5D,%20i%5D%0A%20%20%20%20%20%20%20%20dic%5Bnums%5Bi%5D%5D%20%3D%20i%0A%20%20%20%20return%20%5B%5D%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20nums%20%3D%20%5B2,%207,%2011,%2015%5D%0A%20%20%20%20target%20%3D%2013%0A%20%20%20%20res%20%3D%20two_sum_hash_table%28nums,%20target%29&codeDivHeight=472&codeDivWidth=350&cumulative=false&curInstr=5&heapPrimitives=nevernest&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false"> </iframe></div>
|
||||
<div style="margin-top: 5px;"><a href="https://pythontutor.com/iframe-embed.html#code=def%20two_sum_hash_table%28nums%3A%20list%5Bint%5D,%20target%3A%20int%29%20-%3E%20list%5Bint%5D%3A%0A%20%20%20%20%22%22%22%E6%96%B9%E6%B3%95%E4%BA%8C%EF%BC%9A%E8%BE%85%E5%8A%A9%E5%93%88%E5%B8%8C%E8%A1%A8%22%22%22%0A%20%20%20%20%23%20%E8%BE%85%E5%8A%A9%E5%93%88%E5%B8%8C%E8%A1%A8%EF%BC%8C%E7%A9%BA%E9%97%B4%E5%A4%8D%E6%9D%82%E5%BA%A6%E4%B8%BA%20O%28n%29%0A%20%20%20%20dic%20%3D%20%7B%7D%0A%20%20%20%20%23%20%E5%8D%95%E5%B1%82%E5%BE%AA%E7%8E%AF%EF%BC%8C%E6%97%B6%E9%97%B4%E5%A4%8D%E6%9D%82%E5%BA%A6%E4%B8%BA%20O%28n%29%0A%20%20%20%20for%20i%20in%20range%28len%28nums%29%29%3A%0A%20%20%20%20%20%20%20%20if%20target%20-%20nums%5Bi%5D%20in%20dic%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20return%20%5Bdic%5Btarget%20-%20nums%5Bi%5D%5D,%20i%5D%0A%20%20%20%20%20%20%20%20dic%5Bnums%5Bi%5D%5D%20%3D%20i%0A%20%20%20%20return%20%5B%5D%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20nums%20%3D%20%5B2,%207,%2011,%2015%5D%0A%20%20%20%20target%20%3D%2013%0A%20%20%20%20res%20%3D%20two_sum_hash_table%28nums,%20target%29&codeDivHeight=800&codeDivWidth=600&cumulative=false&curInstr=5&heapPrimitives=nevernest&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false" target="_blank" rel="noopener noreferrer">全螢幕觀看 ></a></div>
|
||||
|
||||
此方法透過雜湊查詢將時間複雜度從 $O(n^2)$ 降至 $O(n)$ ,大幅提升執行效率。
|
||||
|
||||
由於需要維護一個額外的雜湊表,因此空間複雜度為 $O(n)$ 。**儘管如此,該方法的整體時空效率更為均衡,因此它是本題的最優解法**。
|
||||
@@ -0,0 +1,94 @@
|
||||
---
|
||||
comments: true
|
||||
---
|
||||
|
||||
# 10.5 重識搜尋演算法
|
||||
|
||||
<u>搜尋演算法(searching algorithm)</u>用於在資料結構(例如陣列、鏈結串列、樹或圖)中搜索一個或一組滿足特定條件的元素。
|
||||
|
||||
搜尋演算法可根據實現思路分為以下兩類。
|
||||
|
||||
- **透過走訪資料結構來定位目標元素**,例如陣列、鏈結串列、樹和圖的走訪等。
|
||||
- **利用資料組織結構或資料包含的先驗資訊,實現高效元素查詢**,例如二分搜尋、雜湊查詢和二元搜尋樹查詢等。
|
||||
|
||||
不難發現,這些知識點都已在前面的章節中介紹過,因此搜尋演算法對於我們來說並不陌生。在本節中,我們將從更加系統的視角切入,重新審視搜尋演算法。
|
||||
|
||||
## 10.5.1 暴力搜尋
|
||||
|
||||
暴力搜尋透過走訪資料結構的每個元素來定位目標元素。
|
||||
|
||||
- “線性搜尋”適用於陣列和鏈結串列等線性資料結構。它從資料結構的一端開始,逐個訪問元素,直到找到目標元素或到達另一端仍沒有找到目標元素為止。
|
||||
- “廣度優先搜尋”和“深度優先搜尋”是圖和樹的兩種走訪策略。廣度優先搜尋從初始節點開始逐層搜尋,由近及遠地訪問各個節點。深度優先搜尋從初始節點開始,沿著一條路徑走到頭,再回溯並嘗試其他路徑,直到走訪完整個資料結構。
|
||||
|
||||
暴力搜尋的優點是簡單且通用性好,**無須對資料做預處理和藉助額外的資料結構**。
|
||||
|
||||
然而,**此類演算法的時間複雜度為 $O(n)$** ,其中 $n$ 為元素數量,因此在資料量較大的情況下效能較差。
|
||||
|
||||
## 10.5.2 自適應搜尋
|
||||
|
||||
自適應搜尋利用資料的特有屬性(例如有序性)來最佳化搜尋過程,從而更高效地定位目標元素。
|
||||
|
||||
- “二分搜尋”利用資料的有序性實現高效查詢,僅適用於陣列。
|
||||
- “雜湊查詢”利用雜湊表將搜尋資料和目標資料建立為鍵值對對映,從而實現查詢操作。
|
||||
- “樹查詢”在特定的樹結構(例如二元搜尋樹)中,基於比較節點值來快速排除節點,從而定位目標元素。
|
||||
|
||||
此類演算法的優點是效率高,**時間複雜度可達到 $O(\log n)$ 甚至 $O(1)$** 。
|
||||
|
||||
然而,**使用這些演算法往往需要對資料進行預處理**。例如,二分搜尋需要預先對陣列進行排序,雜湊查詢和樹查詢都需要藉助額外的資料結構,維護這些資料結構也需要額外的時間和空間開銷。
|
||||
|
||||
!!! tip
|
||||
|
||||
自適應搜尋演算法常被稱為查詢演算法,**主要用於在特定資料結構中快速檢索目標元素**。
|
||||
|
||||
## 10.5.3 搜尋方法選取
|
||||
|
||||
給定大小為 $n$ 的一組資料,我們可以使用線性搜尋、二分搜尋、樹查詢、雜湊查詢等多種方法從中搜索目標元素。各個方法的工作原理如圖 10-11 所示。
|
||||
|
||||
{ class="animation-figure" }
|
||||
|
||||
<p align="center"> 圖 10-11 多種搜尋策略 </p>
|
||||
|
||||
上述幾種方法的操作效率與特性如表 10-1 所示。
|
||||
|
||||
<p align="center"> 表 10-1 查詢演算法效率對比 </p>
|
||||
|
||||
<div class="center-table" markdown>
|
||||
|
||||
| | 線性搜尋 | 二分搜尋 | 樹查詢 | 雜湊查詢 |
|
||||
| ------------ | -------- | ------------------ | ------------------ | --------------- |
|
||||
| 查詢元素 | $O(n)$ | $O(\log n)$ | $O(\log n)$ | $O(1)$ |
|
||||
| 插入元素 | $O(1)$ | $O(n)$ | $O(\log n)$ | $O(1)$ |
|
||||
| 刪除元素 | $O(n)$ | $O(n)$ | $O(\log n)$ | $O(1)$ |
|
||||
| 額外空間 | $O(1)$ | $O(1)$ | $O(n)$ | $O(n)$ |
|
||||
| 資料預處理 | / | 排序 $O(n \log n)$ | 建樹 $O(n \log n)$ | 建雜湊表 $O(n)$ |
|
||||
| 資料是否有序 | 無序 | 有序 | 有序 | 無序 |
|
||||
|
||||
</div>
|
||||
|
||||
搜尋演算法的選擇還取決於資料體量、搜尋效能要求、資料查詢與更新頻率等。
|
||||
|
||||
**線性搜尋**
|
||||
|
||||
- 通用性較好,無須任何資料預處理操作。假如我們僅需查詢一次資料,那麼其他三種方法的資料預處理的時間比線性搜尋的時間還要更長。
|
||||
- 適用於體量較小的資料,此情況下時間複雜度對效率影響較小。
|
||||
- 適用於資料更新頻率較高的場景,因為該方法不需要對資料進行任何額外維護。
|
||||
|
||||
**二分搜尋**
|
||||
|
||||
- 適用於大資料量的情況,效率表現穩定,最差時間複雜度為 $O(\log n)$ 。
|
||||
- 資料量不能過大,因為儲存陣列需要連續的記憶體空間。
|
||||
- 不適用於高頻增刪資料的場景,因為維護有序陣列的開銷較大。
|
||||
|
||||
**雜湊查詢**
|
||||
|
||||
- 適合對查詢效能要求很高的場景,平均時間複雜度為 $O(1)$ 。
|
||||
- 不適合需要有序資料或範圍查詢的場景,因為雜湊表無法維護資料的有序性。
|
||||
- 對雜湊函式和雜湊衝突處理策略的依賴性較高,具有較大的效能劣化風險。
|
||||
- 不適合資料量過大的情況,因為雜湊表需要額外空間來最大程度地減少衝突,從而提供良好的查詢效能。
|
||||
|
||||
**樹查詢**
|
||||
|
||||
- 適用於海量資料,因為樹節點在記憶體中是分散儲存的。
|
||||
- 適合需要維護有序資料或範圍查詢的場景。
|
||||
- 在持續增刪節點的過程中,二元搜尋樹可能產生傾斜,時間複雜度劣化至 $O(n)$ 。
|
||||
- 若使用 AVL 樹或紅黑樹,則各項操作可在 $O(\log n)$ 效率下穩定執行,但維護樹平衡的操作會增加額外的開銷。
|
||||
@@ -0,0 +1,12 @@
|
||||
---
|
||||
comments: true
|
||||
---
|
||||
|
||||
# 10.6 小結
|
||||
|
||||
- 二分搜尋依賴資料的有序性,透過迴圈逐步縮減一半搜尋區間來進行查詢。它要求輸入資料有序,且僅適用於陣列或基於陣列實現的資料結構。
|
||||
- 暴力搜尋透過走訪資料結構來定位資料。線性搜尋適用於陣列和鏈結串列,廣度優先搜尋和深度優先搜尋適用於圖和樹。此類演算法通用性好,無須對資料進行預處理,但時間複雜度 $O(n)$ 較高。
|
||||
- 雜湊查詢、樹查詢和二分搜尋屬於高效搜尋方法,可在特定資料結構中快速定位目標元素。此類演算法效率高,時間複雜度可達 $O(\log n)$ 甚至 $O(1)$ ,但通常需要藉助額外資料結構。
|
||||
- 實際中,我們需要對資料體量、搜尋效能要求、資料查詢和更新頻率等因素進行具體分析,從而選擇合適的搜尋方法。
|
||||
- 線性搜尋適用於小型或頻繁更新的資料;二分搜尋適用於大型、排序的資料;雜湊查詢適用於對查詢效率要求較高且無須範圍查詢的資料;樹查詢適用於需要維護順序和支持範圍查詢的大型動態資料。
|
||||
- 用雜湊查詢替換線性查詢是一種常用的最佳化執行時間的策略,可將時間複雜度從 $O(n)$ 降至 $O(1)$ 。
|
||||
Reference in New Issue
Block a user