Release Rust code to documents. (#656)

This commit is contained in:
Yudong Jin
2023-07-26 11:00:53 +08:00
committed by GitHub
parent 60162f6fa8
commit 027bdd6510
61 changed files with 1155 additions and 145 deletions
+12
View File
@@ -110,6 +110,12 @@
[class]{}-[func]{binarySearch}
```
=== "Rust"
```rust title="binary_search.rs"
[class]{}-[func]{binary_search}
```
时间复杂度为 $O(\log n)$ 。每轮缩小一半区间,因此二分循环次数为 $\log_2 n$ 。
空间复杂度为 $O(1)$ 。指针 `i` , `j` 使用常数大小空间。
@@ -186,6 +192,12 @@
[class]{}-[func]{binarySearchLCRO}
```
=== "Rust"
```rust title="binary_search.rs"
[class]{}-[func]{binary_search_lcro}
```
如下图所示,在两种区间表示下,二分查找算法的初始化、循环条件和缩小区间操作皆有所不同。
在“双闭区间”表示法中,由于左右边界都被定义为闭区间,因此指针 $i$ 和 $j$ 缩小区间操作也是对称的。这样更不容易出错。因此,**我们通常采用“双闭区间”的写法**。
@@ -118,6 +118,12 @@
[class]{}-[func]{binarySearchLeftEdge}
```
=== "Rust"
```rust title="binary_search_edge.rs"
[class]{}-[func]{binary_search_left_edge}
```
## 查找右边界
类似地,我们也可以二分查找最右边的 `target` 。当 `nums[m] == target` 时,说明大于 `target` 的元素在区间 $[m + 1, j]$ 中,因此执行 `i = m + 1` **使得指针 $i$ 向大于 `target` 的元素靠近**。
@@ -190,6 +196,12 @@
[class]{}-[func]{binarySearchRightEdge}
```
=== "Rust"
```rust title="binary_search_edge.rs"
[class]{}-[func]{binary_search_right_edge}
```
观察下图,搜索最右边元素时指针 $j$ 的作用与搜索最左边元素时指针 $i$ 的作用一致,反之亦然。也就是说,**搜索最左边元素和最右边元素的实现是镜像对称的**。
![查找最左边和最右边元素的对称性](binary_search_edge.assets/binary_search_left_right_edge.png)
@@ -78,6 +78,12 @@
[class]{}-[func]{twoSumBruteForce}
```
=== "Rust"
```rust title="two_sum.rs"
[class]{}-[func]{two_sum_brute_force}
```
此方法的时间复杂度为 $O(n^2)$ ,空间复杂度为 $O(1)$ ,在大数据量下非常耗时。
## 哈希查找:以空间换时间
@@ -166,6 +172,12 @@
[class]{}-[func]{twoSumHashTable}
```
=== "Rust"
```rust title="two_sum.rs"
[class]{}-[func]{two_sum_hash_table}
```
此方法通过哈希查找将时间复杂度从 $O(n^2)$ 降低至 $O(n)$ ,大幅提升运行效率。
由于需要维护一个额外的哈希表,因此空间复杂度为 $O(n)$ 。**尽管如此,该方法的整体时空效率更为均衡,因此它是本题的最优解法**。