Organizing all the code blocks.

This commit is contained in:
Yudong Jin 2022-12-03 01:31:29 +08:00
parent fec56afd5f
commit 9bd5980a81
21 changed files with 2520 additions and 310 deletions

View file

@ -24,14 +24,6 @@ comments: true
int[] nums = { 1, 3, 2, 5, 4 };
```
=== "JavaScript"
```javascript title="array.javascript"
/* 初始化数组 */
var arr = new Array(5).fill(0)
var nums = [1, 3, 2, 5, 4]
```
=== "C++"
```cpp title="array.cpp"
@ -48,6 +40,38 @@ comments: true
nums = [1, 3, 2, 5, 4]
```
=== "Go"
```go title="array.go"
```
=== "JavaScript"
```javascript title="array.js"
/* 初始化数组 */
var arr = new Array(5).fill(0)
var nums = [1, 3, 2, 5, 4]
```
=== "TypeScript"
```typescript title="array.ts"
```
=== "C"
```c title="array.c"
```
=== "C#"
```csharp title="array.cs"
```
## 数组优点
**在数组中访问元素非常高效。** 这是因为在数组中,计算元素的内存地址非常容易。给定数组首个元素的地址、和一个元素的索引,利用以下公式可以直接计算得到该元素的内存地址,从而直接访问此元素。
@ -77,19 +101,6 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
}
```
=== "JavaScript"
```javascript title="array.javascript"
/* 随机返回一个数组元素 */
function randomAccess(nums){
// 在区间 [0, nums.length) 中随机抽取一个数字
const random_index = Math.floor(Math.random() * nums.length)
// 获取并返回随机元素
random_num = nums[random_index]
return random_num
}
```
=== "C++"
```cpp title="array.cpp"
@ -115,6 +126,43 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
return random_num
```
=== "Go"
```go title="array.go"
```
=== "JavaScript"
```javascript title="array.js"
/* 随机返回一个数组元素 */
function randomAccess(nums){
// 在区间 [0, nums.length) 中随机抽取一个数字
const random_index = Math.floor(Math.random() * nums.length)
// 获取并返回随机元素
random_num = nums[random_index]
return random_num
}
```
=== "TypeScript"
```typescript title="array.ts"
```
=== "C"
```c title="array.c"
```
=== "C#"
```csharp title="array.cs"
```
## 数组缺点
**数组在初始化后长度不可变。** 由于系统无法保证数组之后的内存空间是可用的,因此数组长度无法扩展。而若希望扩容数组,则需新建一个数组,然后把原数组元素依次拷贝到新数组,在数组很大的情况下,这是非常耗时的。
@ -135,22 +183,6 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
}
```
=== "JavaScript"
```javascript title="array.javascript"
/* 扩展数组长度 */
function extend(nums, enlarge){
// 初始化一个扩展长度后的数组
let res = new Array(nums.length + enlarge).fill(0)
// 将原数组中的所有元素复制到新数组
for(let i=0; i<nums.length;i++){
res[i] = nums[i]
}
// 返回扩展后的新数组
return res
}
```
=== "C++"
```cpp title="array.cpp"
@ -183,6 +215,46 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
return res
```
=== "Go"
```go title="array.go"
```
=== "JavaScript"
```javascript title="array.js"
/* 扩展数组长度 */
function extend(nums, enlarge){
// 初始化一个扩展长度后的数组
let res = new Array(nums.length + enlarge).fill(0)
// 将原数组中的所有元素复制到新数组
for(let i=0; i<nums.length;i++){
res[i] = nums[i]
}
// 返回扩展后的新数组
return res
}
```
=== "TypeScript"
```typescript title="array.ts"
```
=== "C"
```c title="array.c"
```
=== "C#"
```csharp title="array.cs"
```
**数组中插入或删除元素效率低下。** 假设我们想要在数组中间某位置插入一个元素,由于数组元素在内存中是 “紧挨着的” ,它们之间没有空间再放任何数据。因此,我们不得不将此索引之后的所有元素都向后移动一位,然后再把元素赋值给该索引。删除元素也是类似,需要把此索引之后的元素都向前移动一位。总体看有以下缺点:
- **时间复杂度高:** 数组的插入和删除的平均时间复杂度均为 $O(N)$ ,其中 $N$ 为数组长度。
@ -215,28 +287,6 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
}
```
=== "JavaScript"
```javascript title="array.javascript"
/* 在数组的索引 index 处插入元素 num */
function insert(nums, num, index){
// 把索引 index 以及之后的所有元素向后移动一位
for (let i = nums.length - 1; i >= index; i--) {
nums[i] = nums[i - 1];
}
// 将 num 赋给 index 处元素
nums[index] = num;
}
/* 删除索引 index 处元素 */
function remove(nums, index){
// 把索引 index 之后的所有元素向前移动一位
for (let i = index; i < nums.length - 1; i++) {
nums[i] = nums[i + 1]
}
}
```
=== "C++"
```cpp title="array.cpp"
@ -277,6 +327,52 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
nums[i] = nums[i + 1]
```
=== "Go"
```go title="array.go"
```
=== "JavaScript"
```javascript title="array.js"
/* 在数组的索引 index 处插入元素 num */
function insert(nums, num, index){
// 把索引 index 以及之后的所有元素向后移动一位
for (let i = nums.length - 1; i >= index; i--) {
nums[i] = nums[i - 1];
}
// 将 num 赋给 index 处元素
nums[index] = num;
}
/* 删除索引 index 处元素 */
function remove(nums, index){
// 把索引 index 之后的所有元素向前移动一位
for (let i = index; i < nums.length - 1; i++) {
nums[i] = nums[i + 1]
}
}
```
=== "TypeScript"
```typescript title="array.ts"
```
=== "C"
```c title="array.c"
```
=== "C#"
```csharp title="array.cs"
```
## 数组常用操作
**数组遍历。** 以下介绍两种常用的遍历方法。
@ -298,23 +394,6 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
}
```
=== "JavaScript"
```javascript title="array.javascript"
/* 遍历数组 */
function traverse(nums){
let count = 0
// 通过索引遍历数组
for (let i = 0; i < nums.length; i++) {
count++;
}
// 直接遍历数组
for(let num of nums){
count += 1
}
}
```
=== "C++"
```cpp title="array.cpp"
@ -342,6 +421,47 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
count += 1
```
=== "Go"
```go title="array.go"
```
=== "JavaScript"
```javascript title="array.js"
/* 遍历数组 */
function traverse(nums){
let count = 0
// 通过索引遍历数组
for (let i = 0; i < nums.length; i++) {
count++;
}
// 直接遍历数组
for(let num of nums){
count += 1
}
}
```
=== "TypeScript"
```typescript title="array.ts"
```
=== "C"
```c title="array.c"
```
=== "C#"
```csharp title="array.cs"
```
**数组查找。** 通过遍历数组,查找数组内的指定元素,并输出对应索引。
=== "Java"
@ -357,19 +477,6 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
}
```
=== "JavaScript"
```javascript title="array.javascript"
/* 在数组中查找指定元素 */
function find(nums, target){
for (let i = 0; i < nums.length; i++) {
if (nums[i] == target)
return i;
}
return -1
}
```
=== "C++"
```cpp title="array.cpp"
@ -394,6 +501,43 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
return -1
```
=== "Go"
```go title="array.go"
```
=== "JavaScript"
```javascript title="array.js"
/* 在数组中查找指定元素 */
function find(nums, target){
for (let i = 0; i < nums.length; i++) {
if (nums[i] == target)
return i;
}
return -1
}
```
=== "TypeScript"
```typescript title="array.ts"
```
=== "C"
```c title="array.c"
```
=== "C#"
```csharp title="array.cs"
```
## 数组典型应用
**随机访问。** 如果我们想要随机抽取一些样本,那么可以用数组存储,并生成一个随机序列,根据索引实现样本的随机抽取。

View file

@ -48,6 +48,36 @@ comments: true
self.next = None # 指向下一结点的指针(引用)
```
=== "Go"
```go title=""
```
=== "JavaScript"
```js title=""
```
=== "TypeScript"
```typescript title=""
```
=== "C"
```c title=""
```
=== "C#"
```csharp title=""
```
**尾结点指向什么?** 我们一般将链表的最后一个结点称为「尾结点」,其指向的是「空」,在 Java / C++ / Python 中分别记为 `null` / `nullptr` / `None` 。在不引起歧义下,本书都使用 `null` 来表示空。
**链表初始化方法。** 建立链表分为两步,第一步是初始化各个结点对象,第二步是构建引用指向关系。完成后,即可以从链表的首个结点(即头结点)出发,访问其余所有的结点。
@ -107,6 +137,36 @@ comments: true
n3.next = n4
```
=== "Go"
```go title=""
```
=== "JavaScript"
```js title=""
```
=== "TypeScript"
```typescript title=""
```
=== "C"
```c title=""
```
=== "C#"
```csharp title=""
```
## 链表优点
**在链表中,插入与删除结点的操作效率高。** 例如,如果想在链表中间的两个结点 `A` , `B` 之间插入一个新结点 `P` ,我们只需要改变两个结点指针即可,时间复杂度为 $O(1)$ ,相比数组的插入操作高效很多。在链表中删除某个结点也很方便,只需要改变一个结点指针即可。
@ -176,6 +236,36 @@ comments: true
n0.next = n1
```
=== "Go"
```go title=""
```
=== "JavaScript"
```js title=""
```
=== "TypeScript"
```typescript title=""
```
=== "C"
```c title=""
```
=== "C#"
```csharp title=""
```
## 链表缺点
**链表访问结点效率低。** 上节提到,数组可以在 $O(1)$ 时间下访问任意元素,但链表无法直接访问任意结点。这是因为计算机需要从头结点出发,一个一个地向后遍历到目标结点。例如,倘若想要访问链表索引为 `index` (即第 `index + 1` 个)的结点,那么需要 `index` 次访问操作。
@ -220,6 +310,36 @@ comments: true
return head
```
=== "Go"
```go title=""
```
=== "JavaScript"
```js title=""
```
=== "TypeScript"
```typescript title=""
```
=== "C"
```c title=""
```
=== "C#"
```csharp title=""
```
**链表的内存占用多。** 链表以结点为单位,每个结点除了保存值外,还需额外保存指针(引用)。这意味着同样数据量下,链表比数组需要占用更多内存空间。
## 链表常用操作
@ -272,6 +392,36 @@ comments: true
return -1
```
=== "Go"
```go title=""
```
=== "JavaScript"
```js title=""
```
=== "TypeScript"
```typescript title=""
```
=== "C"
```c title=""
```
=== "C#"
```csharp title=""
```
## 常见链表类型
**单向链表。** 即上述介绍的普通链表。单向链表的结点有「值」和指向下一结点的「指针(引用)」两项数据。我们将首个结点称为头结点,尾结点指向 `null`
@ -315,6 +465,36 @@ comments: true
self.prev = None # 指向前驱结点的指针(引用)
```
=== "Go"
```go title=""
```
=== "JavaScript"
```js title=""
```
=== "TypeScript"
```typescript title=""
```
=== "C"
```c title=""
```
=== "C#"
```csharp title=""
```
![linkedlist_common_types](linked_list.assets/linkedlist_common_types.png)
<p align="center"> Fig. 常见链表类型 </p>

View file

@ -35,6 +35,36 @@ comments: true
list = [1, 3, 2, 5, 4]
```
=== "Go"
```go title="list.go"
```
=== "JavaScript"
```js title="list.js"
```
=== "TypeScript"
```typescript title="list.ts"
```
=== "C"
```c title="list.c"
```
=== "C#"
```csharp title="list.cs"
```
**访问与更新元素。** 列表的底层数据结构是数组,因此可以在 $O(1)$ 时间内访问与更新元素,效率很高。
=== "Java"
@ -67,6 +97,36 @@ comments: true
list[1] = 0 # 将索引 1 处的元素更新为 0
```
=== "Go"
```go title="list.go"
```
=== "JavaScript"
```js title="list.js"
```
=== "TypeScript"
```typescript title="list.ts"
```
=== "C"
```c title="list.c"
```
=== "C#"
```csharp title="list.cs"
```
**在列表中添加、插入、删除元素。** 相对于数组,列表可以自由地添加与删除元素。在列表尾部添加元素的时间复杂度为 $O(1)$ ,但是插入与删除元素的效率仍与数组一样低,时间复杂度为 $O(N)$ 。
=== "Java"
@ -129,6 +189,36 @@ comments: true
list.pop(3) # 删除索引 3 处的元素
```
=== "Go"
```go title="list.go"
```
=== "JavaScript"
```js title="list.js"
```
=== "TypeScript"
```typescript title="list.ts"
```
=== "C"
```c title="list.c"
```
=== "C#"
```csharp title="list.cs"
```
**遍历列表。** 与数组一样,列表可以使用索引遍历,也可以使用 `for-each` 直接遍历。
=== "Java"
@ -177,6 +267,36 @@ comments: true
count += 1
```
=== "Go"
```go title="list.go"
```
=== "JavaScript"
```js title="list.js"
```
=== "TypeScript"
```typescript title="list.ts"
```
=== "C"
```c title="list.c"
```
=== "C#"
```csharp title="list.cs"
```
**拼接两个列表。** 再创建一个新列表 `list1` ,我们可以将其中一个列表拼接到另一个的尾部。
=== "Java"
@ -204,6 +324,36 @@ comments: true
list += list1 # 将列表 list1 拼接到 list 之后
```
=== "Go"
```go title="list.go"
```
=== "JavaScript"
```js title="list.js"
```
=== "TypeScript"
```typescript title="list.ts"
```
=== "C"
```c title="list.c"
```
=== "C#"
```csharp title="list.cs"
```
**排序列表。** 排序也是常用的方法之一,完成列表排序后,我们就可以使用在数组类算法题中经常考察的「二分查找」和「双指针」算法了。
=== "Java"
@ -227,6 +377,36 @@ comments: true
list.sort() # 排序后,列表元素从小到大排列
```
=== "Go"
```go title="list.go"
```
=== "JavaScript"
```js title="list.js"
```
=== "TypeScript"
```typescript title="list.ts"
```
=== "C"
```c title="list.c"
```
=== "C#"
```csharp title="list.cs"
```
## 列表简易实现 *
为了帮助加深对列表的理解,我们在此提供一个列表的简易版本的实现。需要关注三个核心点:
@ -491,3 +671,33 @@ comments: true
# 更新列表容量
self.__capacity = len(self.__nums)
```
=== "Go"
```go title="my_list.go"
```
=== "JavaScript"
```js title="my_list.js"
```
=== "TypeScript"
```typescript title="my_list.ts"
```
=== "C"
```c title="my_list.c"
```
=== "C#"
```csharp title="my_list.cs"
```

View file

@ -99,6 +99,36 @@ comments: true
return a + b + c # 输出数据
```
=== "Go"
```go title=""
```
=== "JavaScript"
```js title=""
```
=== "TypeScript"
```typescript title=""
```
=== "C"
```c title=""
```
=== "C#"
```csharp title=""
```
## 推算方法
空间复杂度的推算方法和时间复杂度总体类似,只是从统计 “计算操作数量” 变为统计 “使用空间大小” 。与时间复杂度不同的是,**我们一般只关注「最差空间复杂度」**。这是因为内存空间是一个硬性要求,我们必须保证在所有输入数据下都有足够的内存空间预留。
@ -140,6 +170,36 @@ comments: true
nums = [0] * n # O(n)
```
=== "Go"
```go title=""
```
=== "JavaScript"
```js title=""
```
=== "TypeScript"
```typescript title=""
```
=== "C"
```c title=""
```
=== "C#"
```csharp title=""
```
**在递归函数中,需要注意统计栈帧空间。** 例如函数 `loop()`,在循环中调用了 $n$ 次 `function()` ,每轮中的 `function()` 都返回并释放了栈帧空间,因此空间复杂度仍为 $O(1)$ 。而递归函数 `recur()` 在运行中会同时存在 $n$ 个未返回的 `recur()` ,从而使用 $O(n)$ 的栈帧空间。
=== "Java"
@ -200,6 +260,36 @@ comments: true
return recur(n - 1)
```
=== "Go"
```go title=""
```
=== "JavaScript"
```js title=""
```
=== "TypeScript"
```typescript title=""
```
=== "C"
```c title=""
```
=== "C#"
```csharp title=""
```
## 常见类型
设输入数据大小为 $n$ ,常见的空间复杂度类型有(从低到高排列)
@ -284,6 +374,36 @@ $$
function()
```
=== "Go"
```go title="space_complexity_types.go"
```
=== "JavaScript"
```js title="space_complexity_types.js"
```
=== "TypeScript"
```typescript title="space_complexity_types.ts"
```
=== "C"
```c title="space_complexity_types.c"
```
=== "C#"
```csharp title="space_complexity_types.cs"
```
### 线性阶 $O(n)$
线性阶常见于元素数量与 $n$ 成正比的数组、链表、栈、队列等。
@ -341,6 +461,36 @@ $$
mapp[i] = str(i)
```
=== "Go"
```go title="space_complexity_types.go"
```
=== "JavaScript"
```js title="space_complexity_types.js"
```
=== "TypeScript"
```typescript title="space_complexity_types.ts"
```
=== "C"
```c title="space_complexity_types.c"
```
=== "C#"
```csharp title="space_complexity_types.cs"
```
以下递归函数会同时存在 $n$ 个未返回的 `algorithm()` 函数,使用 $O(n)$ 大小的栈帧空间。
=== "Java"
@ -375,6 +525,36 @@ $$
linearRecur(n - 1)
```
=== "Go"
```go title="space_complexity_types.go"
```
=== "JavaScript"
```js title="space_complexity_types.js"
```
=== "TypeScript"
```typescript title="space_complexity_types.ts"
```
=== "C"
```c title="space_complexity_types.c"
```
=== "C#"
```csharp title="space_complexity_types.cs"
```
![space_complexity_recursive_linear](space_complexity.assets/space_complexity_recursive_linear.png)
<p align="center"> Fig. 递归函数产生的线性阶空间复杂度 </p>
@ -428,6 +608,36 @@ $$
num_matrix = [[0] * n for _ in range(n)]
```
=== "Go"
```go title="space_complexity_types.go"
```
=== "JavaScript"
```js title="space_complexity_types.js"
```
=== "TypeScript"
```typescript title="space_complexity_types.ts"
```
=== "C"
```c title="space_complexity_types.c"
```
=== "C#"
```csharp title="space_complexity_types.cs"
```
在以下递归函数中,同时存在 $n$ 个未返回的 `algorihtm()` ,并且每个函数中都初始化了一个数组,长度分别为 $n, n-1, n-2, ..., 2, 1$ ,平均长度为 $\frac{n}{2}$ ,因此总体使用 $O(n^2)$ 空间。
=== "Java"
@ -465,6 +675,36 @@ $$
return quadratic_recur(n - 1)
```
=== "Go"
```go title="space_complexity_types.go"
```
=== "JavaScript"
```js title="space_complexity_types.js"
```
=== "TypeScript"
```typescript title="space_complexity_types.ts"
```
=== "C"
```c title="space_complexity_types.c"
```
=== "C#"
```csharp title="space_complexity_types.cs"
```
![space_complexity_recursive_quadratic](space_complexity.assets/space_complexity_recursive_quadratic.png)
<p align="center"> Fig. 递归函数产生的平方阶空间复杂度 </p>
@ -511,6 +751,36 @@ $$
return root
```
=== "Go"
```go title="space_complexity_types.go"
```
=== "JavaScript"
```js title="space_complexity_types.js"
```
=== "TypeScript"
```typescript title="space_complexity_types.ts"
```
=== "C"
```c title="space_complexity_types.c"
```
=== "C#"
```csharp title="space_complexity_types.cs"
```
![space_complexity_exponential](space_complexity.assets/space_complexity_exponential.png)
<p align="center"> Fig. 满二叉树下的指数阶空间复杂度 </p>

View file

@ -20,7 +20,7 @@ comments: true
=== "Java"
```java title="" title="leetcode_two_sum.java"
```java title="leetcode_two_sum.java"
class SolutionBruteForce {
public int[] twoSum(int[] nums, int target) {
int size = nums.length;
@ -85,6 +85,30 @@ comments: true
}
```
=== "JavaScript"
```js title="leetcode_two_sum.js"
```
=== "TypeScript"
```typescript title="leetcode_two_sum.ts"
```
=== "C"
```c title="leetcode_two_sum.c"
```
=== "C#"
```csharp title="leetcode_two_sum.cs"
```
### 方法二:辅助哈希表
时间复杂度 $O(N)$ ,空间复杂度 $O(N)$ ,属于「空间换时间」。
@ -93,7 +117,7 @@ comments: true
=== "Java"
```java title="" title="leetcode_two_sum.java"
```java title="leetcode_two_sum.java"
class SolutionHashMap {
public int[] twoSum(int[] nums, int target) {
int size = nums.length;
@ -163,3 +187,27 @@ comments: true
return nil
}
```
=== "JavaScript"
```js title="leetcode_two_sum.js"
```
=== "TypeScript"
```typescript title="leetcode_two_sum.ts"
```
=== "C"
```c title="leetcode_two_sum.c"
```
=== "C#"
```csharp title="leetcode_two_sum.cs"
```

View file

@ -61,6 +61,36 @@ $$
print(0) # 5 ns
```
=== "Go"
```go title=""
```
=== "JavaScript"
```js title=""
```
=== "TypeScript"
```typescript title=""
```
=== "C"
```c title=""
```
=== "C#"
```csharp title=""
```
但实际上, **统计算法的运行时间既不合理也不现实。** 首先,我们不希望预估时间和运行平台绑定,毕竟算法需要跑在各式各样的平台之上。其次,我们很难获知每一种操作的运行时间,这为预估过程带来了极大的难度。
## 统计时间增长趋势
@ -131,6 +161,36 @@ $$
print(0)
```
=== "Go"
```go title=""
```
=== "JavaScript"
```js title=""
```
=== "TypeScript"
```typescript title=""
```
=== "C"
```c title=""
```
=== "C#"
```csharp title=""
```
![time_complexity_first_example](time_complexity.assets/time_complexity_first_example.png)
<p align="center"> Fig. 算法 A, B, C 的时间增长趋势 </p>
@ -192,6 +252,36 @@ $$
}
```
=== "Go"
```go title=""
```
=== "JavaScript"
```js title=""
```
=== "TypeScript"
```typescript title=""
```
=== "C"
```c title=""
```
=== "C#"
```csharp title=""
```
$T(n)$ 是个一次函数,说明时间增长趋势是线性的,因此易得时间复杂度是线性阶。
我们将线性阶的时间复杂度记为 $O(n)$ ,这个数学符号被称为「大 $O$ 记号 Big-$O$ Notation」代表函数 $T(n)$ 的「渐进上界 asymptotic upper bound」。
@ -296,6 +386,36 @@ $$
print(0)
```
=== "Go"
```go title=""
```
=== "JavaScript"
```js title=""
```
=== "TypeScript"
```typescript title=""
```
=== "C"
```c title=""
```
=== "C#"
```csharp title=""
```
### 2. 判断渐进上界
**时间复杂度由多项式 $T(n)$ 中最高阶的项来决定**。这是因为在 $n$ 趋于无穷大时,最高阶的项将处于主导作用,其它项的影响都可以被忽略。
@ -341,7 +461,7 @@ $$
=== "Java"
```java title="" title="time_complexity_types.java"
```java title="time_complexity_types.java"
/* 常数阶 */
int constant(int n) {
int count = 0;
@ -377,13 +497,43 @@ $$
return count
```
=== "Go"
```go title="time_complexity_types.go"
```
=== "JavaScript"
```js title="time_complexity_types.js"
```
=== "TypeScript"
```typescript title="time_complexity_types.ts"
```
=== "C"
```c title="time_complexity_types.c"
```
=== "C#"
```csharp title="time_complexity_types.cs"
```
### 线性阶 $O(n)$
线性阶的操作数量相对输入数据大小成线性级别增长。线性阶常出现于单层循环。
=== "Java"
```java title="" title="time_complexity_types.java"
```java title="time_complexity_types.java"
/* 线性阶 */
int linear(int n) {
int count = 0;
@ -416,6 +566,36 @@ $$
return count
```
=== "Go"
```go title="time_complexity_types.go"
```
=== "JavaScript"
```js title="time_complexity_types.js"
```
=== "TypeScript"
```typescript title="time_complexity_types.ts"
```
=== "C"
```c title="time_complexity_types.c"
```
=== "C#"
```csharp title="time_complexity_types.cs"
```
「遍历数组」和「遍历链表」等操作,时间复杂度都为 $O(n)$ ,其中 $n$ 为数组或链表的长度。
!!! tip
@ -424,7 +604,7 @@ $$
=== "Java"
```java title="" title="time_complexity_types.java"
```java title="time_complexity_types.java"
/* 线性阶(遍历数组) */
int arrayTraversal(int[] nums) {
int count = 0;
@ -462,13 +642,43 @@ $$
return count
```
=== "Go"
```go title="time_complexity_types.go"
```
=== "JavaScript"
```js title="time_complexity_types.js"
```
=== "TypeScript"
```typescript title="time_complexity_types.ts"
```
=== "C"
```c title="time_complexity_types.c"
```
=== "C#"
```csharp title="time_complexity_types.cs"
```
### 平方阶 $O(n^2)$
平方阶的操作数量相对输入数据大小成平方级别增长。平方阶常出现于嵌套循环,外层循环和内层循环都为 $O(n)$ ,总体为 $O(n^2)$ 。
=== "Java"
```java title="" title="time_complexity_types.java"
```java title="time_complexity_types.java"
/* 平方阶 */
int quadratic(int n) {
int count = 0;
@ -511,6 +721,36 @@ $$
return count
```
=== "Go"
```go title="time_complexity_types.go"
```
=== "JavaScript"
```js title="time_complexity_types.js"
```
=== "TypeScript"
```typescript title="time_complexity_types.ts"
```
=== "C"
```c title="time_complexity_types.c"
```
=== "C#"
```csharp title="time_complexity_types.cs"
```
![time_complexity_constant_linear_quadratic](time_complexity.assets/time_complexity_constant_linear_quadratic.png)
<p align="center"> Fig. 常数阶、线性阶、平方阶的时间复杂度 </p>
@ -523,7 +763,7 @@ $$
=== "Java"
```java title="" title="time_complexity_types.java"
```java title="time_complexity_types.java"
/* 平方阶(冒泡排序) */
int bubbleSort(int[] nums) {
int count = 0; // 计数器
@ -586,6 +826,36 @@ $$
return count
```
=== "Go"
```go title="time_complexity_types.go"
```
=== "JavaScript"
```js title="time_complexity_types.js"
```
=== "TypeScript"
```typescript title="time_complexity_types.ts"
```
=== "C"
```c title="time_complexity_types.c"
```
=== "C#"
```csharp title="time_complexity_types.cs"
```
### 指数阶 $O(2^n)$
!!! note
@ -596,7 +866,7 @@ $$
=== "Java"
```java title="" title="time_complexity_types.java"
```java title="time_complexity_types.java"
/* 指数阶(循环实现) */
int exponential(int n) {
int count = 0, base = 1;
@ -645,6 +915,36 @@ $$
return count
```
=== "Go"
```go title="time_complexity_types.go"
```
=== "JavaScript"
```js title="time_complexity_types.js"
```
=== "TypeScript"
```typescript title="time_complexity_types.ts"
```
=== "C"
```c title="time_complexity_types.c"
```
=== "C#"
```csharp title="time_complexity_types.cs"
```
![time_complexity_exponential](time_complexity.assets/time_complexity_exponential.png)
<p align="center"> Fig. 指数阶的时间复杂度 </p>
@ -653,7 +953,7 @@ $$
=== "Java"
```java title="" title="time_complexity_types.java"
```java title="time_complexity_types.java"
/* 指数阶(递归实现) */
int expRecur(int n) {
if (n == 1) return 1;
@ -680,6 +980,36 @@ $$
return exp_recur(n - 1) + exp_recur(n - 1) + 1
```
=== "Go"
```go title="time_complexity_types.go"
```
=== "JavaScript"
```js title="time_complexity_types.js"
```
=== "TypeScript"
```typescript title="time_complexity_types.ts"
```
=== "C"
```c title="time_complexity_types.c"
```
=== "C#"
```csharp title="time_complexity_types.cs"
```
### 对数阶 $O(\log n)$
对数阶与指数阶正好相反,后者反映 “每轮增加到两倍的情况” ,而前者反映 “每轮缩减到一半的情况” 。对数阶仅次于常数阶,时间增长的很慢,是理想的时间复杂度。
@ -690,7 +1020,7 @@ $$
=== "Java"
```java title="" title="time_complexity_types.java"
```java title="time_complexity_types.java"
/* 对数阶(循环实现) */
int logarithmic(float n) {
int count = 0;
@ -728,6 +1058,36 @@ $$
return count
```
=== "Go"
```go title="time_complexity_types.go"
```
=== "JavaScript"
```js title="time_complexity_types.js"
```
=== "TypeScript"
```typescript title="time_complexity_types.ts"
```
=== "C"
```c title="time_complexity_types.c"
```
=== "C#"
```csharp title="time_complexity_types.cs"
```
![time_complexity_logarithmic](time_complexity.assets/time_complexity_logarithmic.png)
<p align="center"> Fig. 对数阶的时间复杂度 </p>
@ -736,7 +1096,7 @@ $$
=== "Java"
```java title="" title="time_complexity_types.java"
```java title="time_complexity_types.java"
/* 对数阶(递归实现) */
int logRecur(float n) {
if (n <= 1) return 0;
@ -763,6 +1123,36 @@ $$
return log_recur(n / 2) + 1
```
=== "Go"
```go title="time_complexity_types.go"
```
=== "JavaScript"
```js title="time_complexity_types.js"
```
=== "TypeScript"
```typescript title="time_complexity_types.ts"
```
=== "C"
```c title="time_complexity_types.c"
```
=== "C#"
```csharp title="time_complexity_types.cs"
```
### 线性对数阶 $O(n \log n)$
线性对数阶常出现于嵌套循环中,两层循环的时间复杂度分别为 $O(\log n)$ 和 $O(n)$ 。
@ -771,7 +1161,7 @@ $$
=== "Java"
```java title="" title="time_complexity_types.java"
```java title="time_complexity_types.java"
/* 线性对数阶 */
int linearLogRecur(float n) {
if (n <= 1) return 1;
@ -812,6 +1202,36 @@ $$
return count
```
=== "Go"
```go title="time_complexity_types.go"
```
=== "JavaScript"
```js title="time_complexity_types.js"
```
=== "TypeScript"
```typescript title="time_complexity_types.ts"
```
=== "C"
```c title="time_complexity_types.c"
```
=== "C#"
```csharp title="time_complexity_types.cs"
```
![time_complexity_logarithmic_linear](time_complexity.assets/time_complexity_logarithmic_linear.png)
<p align="center"> Fig. 线性对数阶的时间复杂度 </p>
@ -828,7 +1248,7 @@ $$
=== "Java"
```java title="" title="time_complexity_types.java"
```java title="time_complexity_types.java"
/* 阶乘阶(递归实现) */
int factorialRecur(int n) {
if (n == 0) return 1;
@ -869,6 +1289,36 @@ $$
return count
```
=== "Go"
```go title="time_complexity_types.go"
```
=== "JavaScript"
```js title="time_complexity_types.js"
```
=== "TypeScript"
```typescript title="time_complexity_types.ts"
```
=== "C"
```c title="time_complexity_types.c"
```
=== "C#"
```csharp title="time_complexity_types.cs"
```
![time_complexity_factorial](time_complexity.assets/time_complexity_factorial.png)
<p align="center"> Fig. 阶乘阶的时间复杂度 </p>
@ -884,7 +1334,7 @@ $$
=== "Java"
```java title="" title="worst_best_time_complexity.java"
```java title="worst_best_time_complexity.java"
public class worst_best_time_complexity {
/* 生成一个数组,元素为 { 1, 2, ..., n },顺序被打乱 */
static int[] randomNumbers(int n) {
@ -994,6 +1444,36 @@ $$
print("数字 1 的索引为", index)
```
=== "Go"
```go title="worst_best_time_complexity.go"
```
=== "JavaScript"
```js title="worst_best_time_complexity.js"
```
=== "TypeScript"
```typescript title="worst_best_time_complexity.ts"
```
=== "C"
```c title="worst_best_time_complexity.c"
```
=== "C#"
```csharp title="worst_best_time_complexity.cs"
```
!!! tip
我们在实际应用中很少使用「最佳时间复杂度」,因为往往只有很小概率下才能达到,会带来一定的误导性。反之,「最差时间复杂度」最为实用,因为它给出了一个 “效率安全值” ,让我们可以放心地使用算法。

View file

@ -46,7 +46,7 @@ comments: true
=== "Java"
```java
```java title=""
/* 使用多种「基本数据类型」来初始化「数组」 */
int[] numbers = new int[5];
float[] decimals = new float[5];
@ -66,6 +66,36 @@ comments: true
```
=== "Go"
```go title=""
```
=== "JavaScript"
```js title=""
```
=== "TypeScript"
```typescript title=""
```
=== "C"
```c title=""
```
=== "C#"
```csharp title=""
```
## 计算机内存
在计算机中,内存和硬盘是两种主要的存储硬件设备。「硬盘」主要用于长期存储数据,容量较大(通常可达到 TB 级别)、速度较慢。「内存」用于运行程序时暂存数据,速度更快,但容量较小(通常为 GB 级别)。

View file

@ -102,6 +102,42 @@ $$
}
```
=== "Python"
```python title="binary_search.py"
```
=== "Go"
```go title="binary_search.go"
```
=== "JavaScript"
```js title="binary_search.js"
```
=== "TypeScript"
```typescript title="binary_search.ts"
```
=== "C"
```c title="binary_search.c"
```
=== "C#"
```csharp title="binary_search.cs"
```
### “左闭右开” 实现
当然,我们也可以使用 “左闭右开” 的表示方法,写出相同功能的二分查找代码。
@ -150,6 +186,42 @@ $$
}
```
=== "Python"
```python title="binary_search.py"
```
=== "Go"
```go title="binary_search.go"
```
=== "JavaScript"
```js title="binary_search.js"
```
=== "TypeScript"
```typescript title="binary_search.ts"
```
=== "C"
```c title="binary_search.c"
```
=== "C#"
```csharp title="binary_search.cs"
```
### 两种表示对比
对比下来,两种表示的代码写法有以下不同点:
@ -171,15 +243,16 @@ $$
=== "Java"
```java
```java title=""
// (i + j) 有可能超出 int 的取值范围
int m = (i + j) / 2;
// 更换为此写法则不会越界
int m = i + (j - i) / 2;
```
=== "C++"
```cpp
```cpp title=""
// (i + j) 有可能超出 int 的取值范围
int m = (i + j) / 2;
// 更换为此写法则不会越界
@ -188,11 +261,41 @@ $$
=== "Python"
```py
```py title=""
# Python 中的数字理论上可以无限大(取决于内存)
# 因此无需考虑大数越界问题
```
=== "Go"
```go title=""
```
=== "JavaScript"
```js title=""
```
=== "TypeScript"
```typescript title=""
```
=== "C"
```c title=""
```
=== "C#"
```csharp title=""
```
## 复杂度分析
**时间复杂度 $O(\log n)$ ** 其中 $n$ 为数组或链表长度;每轮排除一半的区间,因此循环轮数为 $\log_2 n$ ,使用 $O(\log n)$ 时间。

View file

@ -40,6 +40,42 @@ comments: true
}
```
=== "Python"
```python title="hashing_search.py"
```
=== "Go"
```go title="hashing_search.go"
```
=== "JavaScript"
```js title="hashing_search.js"
```
=== "TypeScript"
```typescript title="hashing_search.ts"
```
=== "C"
```c title="hashing_search.c"
```
=== "C#"
```csharp title="hashing_search.cs"
```
再比如,如果我们想要给定一个目标结点值 `target` ,获取对应的链表结点对象,那么也可以使用哈希查找实现。
![hash_search_listnode](hashing_search.assets/hash_search_listnode.png)
@ -68,6 +104,42 @@ comments: true
}
```
=== "Python"
```python title="hashing_search.py"
```
=== "Go"
```go title="hashing_search.go"
```
=== "JavaScript"
```js title="hashing_search.js"
```
=== "TypeScript"
```typescript title="hashing_search.ts"
```
=== "C"
```c title="hashing_search.c"
```
=== "C#"
```csharp title="hashing_search.cs"
```
## 复杂度分析
**时间复杂度:** $O(1)$ ,哈希表的查找操作使用 $O(1)$ 时间。

View file

@ -44,6 +44,42 @@ comments: true
}
```
=== "Python"
```python title="linear_search.py"
```
=== "Go"
```go title="linear_search.go"
```
=== "JavaScript"
```js title="linear_search.js"
```
=== "TypeScript"
```typescript title="linear_search.ts"
```
=== "C"
```c title="linear_search.c"
```
=== "C#"
```csharp title="linear_search.cs"
```
再比如,我们想要在给定一个目标结点值 `target` ,返回此结点对象,也可以在链表中进行线性查找。
=== "Java"
@ -80,6 +116,42 @@ comments: true
}
```
=== "Python"
```python title="linear_search.py"
```
=== "Go"
```go title="linear_search.go"
```
=== "JavaScript"
```js title="linear_search.js"
```
=== "TypeScript"
```typescript title="linear_search.ts"
```
=== "C"
```c title="linear_search.c"
```
=== "C#"
```csharp title="linear_search.cs"
```
## 复杂度分析
**时间复杂度 $O(n)$ ** 其中 $n$ 为数组或链表长度。

View file

@ -1,3 +1,7 @@
---
comments: true
---
# 小结
- 线性查找是一种最基础的查找方法,通过遍历数据结构 + 判断条件实现查找。

View file

@ -74,26 +74,6 @@ comments: true
}
```
=== "JavaScript"
```js title="bubble_sort.js"
/* 冒泡排序 */
function bubbleSort(nums) {
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
for (let i = nums.length - 1; i > 0; i--) {
// 内循环:冒泡操作
for (let j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// 交换 nums[j] 与 nums[j + 1]
let tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
}
}
}
}
```
=== "C++"
```cpp title="bubble_sort.cpp"
@ -129,6 +109,50 @@ comments: true
nums[j], nums[j + 1] = nums[j + 1], nums[j]
```
=== "Go"
```go title="bubble_sort.go"
```
=== "JavaScript"
```js title="bubble_sort.js"
/* 冒泡排序 */
function bubbleSort(nums) {
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
for (let i = nums.length - 1; i > 0; i--) {
// 内循环:冒泡操作
for (let j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// 交换 nums[j] 与 nums[j + 1]
let tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
}
}
}
}
```
=== "TypeScript"
```typescript title="bubble_sort.ts"
```
=== "C"
```c title="bubble_sort.c"
```
=== "C#"
```csharp title="bubble_sort.cs"
```
## 算法特性
**时间复杂度 $O(n^2)$ ** 各轮「冒泡」遍历的数组长度为 $n - 1$ , $n - 2$ , $\cdots$ , $2$ , $1$ 次,求和为 $\frac{(n - 1) n}{2}$ ,因此使用 $O(n^2)$ 时间。
@ -170,29 +194,6 @@ comments: true
}
```
=== "JavaScript"
```js title="bubble_sort.js"
/* 冒泡排序(标志优化)*/
function bubbleSortWithFlag(nums) {
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
for (let i = nums.length - 1; i > 0; i--) {
let flag = false; // 初始化标志位
// 内循环:冒泡操作
for (let j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// 交换 nums[j] 与 nums[j + 1]
let tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
flag = true; // 记录交换元素
}
}
if (!flag) break; // 此轮冒泡未交换任何元素,直接跳出
}
}
```
=== "C++"
```cpp title="bubble_sort.cpp"
@ -234,3 +235,50 @@ comments: true
if not flag:
break # 此轮冒泡未交换任何元素,直接跳出
```
=== "Go"
```go title="bubble_sort.go"
```
=== "JavaScript"
```js title="bubble_sort.js"
/* 冒泡排序(标志优化)*/
function bubbleSortWithFlag(nums) {
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
for (let i = nums.length - 1; i > 0; i--) {
let flag = false; // 初始化标志位
// 内循环:冒泡操作
for (let j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// 交换 nums[j] 与 nums[j + 1]
let tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
flag = true; // 记录交换元素
}
}
if (!flag) break; // 此轮冒泡未交换任何元素,直接跳出
}
}
```
=== "TypeScript"
```typescript title="bubble_sort.ts"
```
=== "C"
```c title="bubble_sort.c"
```
=== "C#"
```csharp title="bubble_sort.cs"
```

View file

@ -42,24 +42,6 @@ comments: true
}
```
=== "JavaScript"
```js title="insertion_sort.js"
/* 插入排序 */
function insertionSort(nums) {
// 外循环base = nums[1], nums[2], ..., nums[n-1]
for (let i = 1; i < nums.length; i++) {
let base = nums[i], j = i - 1;
// 内循环:将 base 插入到左边的正确位置
while (j >= 0 && nums[j] > base) {
nums[j + 1] = nums[j]; // 1. 将 nums[j] 向右移动一位
j--;
}
nums[j + 1] = base; // 2. 将 base 赋值到正确位置
}
}
```
=== "C++"
```cpp title="insertion_sort.cpp"
@ -94,6 +76,48 @@ comments: true
nums[j + 1] = base # 2. 将 base 赋值到正确位置
```
=== "Go"
```go title="insertion_sort.go"
```
=== "JavaScript"
```js title="insertion_sort.js"
/* 插入排序 */
function insertionSort(nums) {
// 外循环base = nums[1], nums[2], ..., nums[n-1]
for (let i = 1; i < nums.length; i++) {
let base = nums[i], j = i - 1;
// 内循环:将 base 插入到左边的正确位置
while (j >= 0 && nums[j] > base) {
nums[j + 1] = nums[j]; // 1. 将 nums[j] 向右移动一位
j--;
}
nums[j + 1] = base; // 2. 将 base 赋值到正确位置
}
}
```
=== "TypeScript"
```typescript title="insertion_sort.ts"
```
=== "C"
```c title="insertion_sort.c"
```
=== "C#"
```csharp title="insertion_sort.cs"
```
## 算法特性
**时间复杂度 $O(n^2)$ ** 最差情况下,各轮插入操作循环 $n - 1$ , $n-2$ , $\cdots$ , $2$ , $1$ 次,求和为 $\frac{(n - 1) n}{2}$ ,使用 $O(n^2)$ 时间。

View file

@ -103,51 +103,6 @@ comments: true
}
```
=== "JavaScript"
```js title="merge_sort.js"
/**
* 合并左子数组和右子数组
* 左子数组区间 [left, mid]
* 右子数组区间 [mid + 1, right]
*/
function merge(nums, left, mid, right) {
// 初始化辅助数组
let tmp = nums.slice(left, right + 1);
// 左子数组的起始索引和结束索引
let leftStart = left - left, leftEnd = mid - left;
// 右子数组的起始索引和结束索引
let rightStart = mid + 1 - left, rightEnd = right - left;
// i, j 分别指向左子数组、右子数组的首元素
let i = leftStart, j = rightStart;
// 通过覆盖原数组 nums 来合并左子数组和右子数组
for (let k = left; k <= right; k++) {
// 若 “左子数组已全部合并完”,则选取右子数组元素,并且 j++
if (i > leftEnd) {
nums[k] = tmp[j++];
// 否则,若 “右子数组已全部合并完” 或 “左子数组元素 < 右子数组元素则选取左子数组元素并且 i++
} else if (j > rightEnd || tmp[i] <= tmp[j]) {
nums[k] = tmp[i++];
// 否则,若 “左子数组元素 > 右子数组元素”,则选取右子数组元素,并且 j++
} else {
nums[k] = tmp[j++];
}
}
}
/* 归并排序 */
function mergeSort(nums, left, right) {
// 终止条件
if (left >= right) return; // 当子数组长度为 1 时终止递归
// 划分阶段
let mid = Math.floor((left + right) / 2); // 计算中点
mergeSort(nums, left, mid); // 递归左子数组
mergeSort(nums, mid + 1, right); // 递归右子数组
// 合并阶段
merge(nums, left, mid, right);
}
```
=== "C++"
```cpp title="merge_sort.cpp"
@ -237,6 +192,75 @@ comments: true
merge(nums, left, mid, right)
```
=== "Go"
```go title="merge_sort.go"
```
=== "JavaScript"
```js title="merge_sort.js"
/**
* 合并左子数组和右子数组
* 左子数组区间 [left, mid]
* 右子数组区间 [mid + 1, right]
*/
function merge(nums, left, mid, right) {
// 初始化辅助数组
let tmp = nums.slice(left, right + 1);
// 左子数组的起始索引和结束索引
let leftStart = left - left, leftEnd = mid - left;
// 右子数组的起始索引和结束索引
let rightStart = mid + 1 - left, rightEnd = right - left;
// i, j 分别指向左子数组、右子数组的首元素
let i = leftStart, j = rightStart;
// 通过覆盖原数组 nums 来合并左子数组和右子数组
for (let k = left; k <= right; k++) {
// 若 “左子数组已全部合并完”,则选取右子数组元素,并且 j++
if (i > leftEnd) {
nums[k] = tmp[j++];
// 否则,若 “右子数组已全部合并完” 或 “左子数组元素 < 右子数组元素则选取左子数组元素并且 i++
} else if (j > rightEnd || tmp[i] <= tmp[j]) {
nums[k] = tmp[i++];
// 否则,若 “左子数组元素 > 右子数组元素”,则选取右子数组元素,并且 j++
} else {
nums[k] = tmp[j++];
}
}
}
/* 归并排序 */
function mergeSort(nums, left, right) {
// 终止条件
if (left >= right) return; // 当子数组长度为 1 时终止递归
// 划分阶段
let mid = Math.floor((left + right) / 2); // 计算中点
mergeSort(nums, left, mid); // 递归左子数组
mergeSort(nums, mid + 1, right); // 递归右子数组
// 合并阶段
merge(nums, left, mid, right);
}
```
=== "TypeScript"
```typescript title="merge_sort.ts"
```
=== "C"
```c title="merge_sort.c"
```
=== "C#"
```csharp title="merge_sort.cs"
```
下面重点解释一下合并方法 `merge()` 的流程:
1. 初始化一个辅助数组 `tmp` 暂存待合并区间 `[left, right]` 内的元素,后续通过覆盖原数组 `nums` 的元素来实现合并;

View file

@ -61,35 +61,6 @@ comments: true
}
```
=== "JavaScript"
``` js title="quick_sort.js"
/* 元素交换 */
function swap(nums, i, j) {
let tmp = nums[i]
nums[i] = nums[j]
nums[j] = tmp
}
/* 哨兵划分 */
function partition(nums, left, right){
// 以 nums[left] 作为基准数
let i = left, j = right
while(i < j){
while(i < j && nums[j] >= nums[left]){
j -= 1 // 从右向左找首个小于基准数的元素
}
while(i < j && nums[i] <= nums[left]){
i += 1 // 从左向右找首个大于基准数的元素
}
// 元素交换
swap(nums, i, j) // 交换这两个元素
}
swap(nums, i, left) // 将基准数交换至两子数组的分界线
return i // 返回基准数的索引
}
```
=== "C++"
```cpp title="quick_sort.cpp"
@ -135,6 +106,59 @@ comments: true
return i # 返回基准数的索引
```
=== "Go"
```go title="quick_sort.go"
```
=== "JavaScript"
``` js title="quick_sort.js"
/* 元素交换 */
function swap(nums, i, j) {
let tmp = nums[i]
nums[i] = nums[j]
nums[j] = tmp
}
/* 哨兵划分 */
function partition(nums, left, right){
// 以 nums[left] 作为基准数
let i = left, j = right
while(i < j){
while(i < j && nums[j] >= nums[left]){
j -= 1 // 从右向左找首个小于基准数的元素
}
while(i < j && nums[i] <= nums[left]){
i += 1 // 从左向右找首个大于基准数的元素
}
// 元素交换
swap(nums, i, j) // 交换这两个元素
}
swap(nums, i, left) // 将基准数交换至两子数组的分界线
return i // 返回基准数的索引
}
```
=== "TypeScript"
```typescript title="quick_sort.ts"
```
=== "C"
```c title="quick_sort.c"
```
=== "C#"
```csharp title="quick_sort.cs"
```
!!! note "快速排序的分治思想"
哨兵划分的实质是将 **一个长数组的排序问题** 简化为 **两个短数组的排序问题**
@ -167,21 +191,6 @@ comments: true
}
```
=== "JavaScript"
```js title="quick_sort.js"
/* 快速排序 */
function quickSort(nums, left, right){
// 子数组长度为 1 时终止递归
if(left >= right) return
// 哨兵划分
const pivot = partition(nums, left, right)
// 递归左子数组、右子数组
quick_sort(nums, left, pivot - 1)
quick_sort(nums, pivot + 1, right)
}
```
=== "C++"
```cpp title="quick_sort.cpp"
@ -213,6 +222,45 @@ comments: true
self.quick_sort(nums, pivot + 1, right)
```
=== "Go"
```go title="quick_sort.go"
```
=== "JavaScript"
```js title="quick_sort.js"
/* 快速排序 */
function quickSort(nums, left, right){
// 子数组长度为 1 时终止递归
if(left >= right) return
// 哨兵划分
const pivot = partition(nums, left, right)
// 递归左子数组、右子数组
quick_sort(nums, left, pivot - 1)
quick_sort(nums, pivot + 1, right)
}
```
=== "TypeScript"
```typescript title="quick_sort.ts"
```
=== "C"
```c title="quick_sort.c"
```
=== "C#"
```csharp title="quick_sort.cs"
```
## 算法特性
**平均时间复杂度 $O(n \log n)$ ** 平均情况下,哨兵划分的递归层数为 $\log n$ ,每层中的总循环数为 $n$ ,总体使用 $O(n \log n)$ 时间。
@ -269,32 +317,6 @@ comments: true
}
```
=== "JavaScript"
```js title="quick_sort.js"
/* 选取三个元素的中位数 */
function medianThree(nums, left, mid, right) {
// 使用了异或操作来简化代码
// 异或规则为 0 ^ 0 = 1 ^ 1 = 0, 0 ^ 1 = 1 ^ 0 = 1
if ((nums[left] > nums[mid]) ^ (nums[left] > nums[right]))
return left;
else if ((nums[mid] < nums[left]) ^ (nums[mid] < nums[right]))
return mid;
else
return right;
}
/* 哨兵划分(三数取中值) */
function partition(nums, left, right) {
// 选取三个候选元素的中位数
let med = medianThree(nums, left, Math.floor((left + right) / 2), right);
// 将中位数交换至数组最左端
swap(nums, left, med);
// 以 nums[left] 作为基准数
// 下同省略...
}
```
=== "C++"
```cpp title="quick_sort.cpp"
@ -344,6 +366,56 @@ comments: true
# 下同省略...
```
=== "Go"
```go title="quick_sort.go"
```
=== "JavaScript"
```js title="quick_sort.js"
/* 选取三个元素的中位数 */
function medianThree(nums, left, mid, right) {
// 使用了异或操作来简化代码
// 异或规则为 0 ^ 0 = 1 ^ 1 = 0, 0 ^ 1 = 1 ^ 0 = 1
if ((nums[left] > nums[mid]) ^ (nums[left] > nums[right]))
return left;
else if ((nums[mid] < nums[left]) ^ (nums[mid] < nums[right]))
return mid;
else
return right;
}
/* 哨兵划分(三数取中值) */
function partition(nums, left, right) {
// 选取三个候选元素的中位数
let med = medianThree(nums, left, Math.floor((left + right) / 2), right);
// 将中位数交换至数组最左端
swap(nums, left, med);
// 以 nums[left] 作为基准数
// 下同省略...
}
```
=== "TypeScript"
```typescript title="quick_sort.ts"
```
=== "C"
```c title="quick_sort.c"
```
=== "C#"
```csharp title="quick_sort.cs"
```
## 尾递归优化
**普通快速排序在某些输入下的空间效率变差。** 仍然以完全倒序的输入数组为例,由于每轮哨兵划分后右子数组长度为 0 ,那么将形成一个高度为 $n - 1$ 的递归树,此时使用的栈帧空间大小劣化至 $O(n)$ 。
@ -371,27 +443,6 @@ comments: true
}
```
=== "JavaScript"
```js title="quick_sort.js"
/* 快速排序(尾递归优化) */
quickSort(nums, left, right) {
// 子数组长度为 1 时终止
while (left < right) {
// 哨兵划分操作
let pivot = partition(nums, left, right);
// 对两个子数组中较短的那个执行快排
if (pivot - left < right - pivot) {
quickSort(nums, left, pivot - 1); // 递归排序左子数组
left = pivot + 1; // 剩余待排序区间为 [pivot + 1, right]
} else {
quickSort(nums, pivot + 1, right); // 递归排序右子数组
right = pivot - 1; // 剩余待排序区间为 [left, pivot - 1]
}
}
}
```
=== "C++"
```cpp title="quick_sort.cpp"
@ -430,3 +481,48 @@ comments: true
self.quick_sort(nums, pivot + 1, right) # 递归排序右子数组
right = pivot - 1 # 剩余待排序区间为 [left, pivot - 1]
```
=== "Go"
```go title="quick_sort.go"
```
=== "JavaScript"
```js title="quick_sort.js"
/* 快速排序(尾递归优化) */
quickSort(nums, left, right) {
// 子数组长度为 1 时终止
while (left < right) {
// 哨兵划分操作
let pivot = partition(nums, left, right);
// 对两个子数组中较短的那个执行快排
if (pivot - left < right - pivot) {
quickSort(nums, left, pivot - 1); // 递归排序左子数组
left = pivot + 1; // 剩余待排序区间为 [pivot + 1, right]
} else {
quickSort(nums, pivot + 1, right); // 递归排序右子数组
right = pivot - 1; // 剩余待排序区间为 [left, pivot - 1]
}
}
}
```
=== "TypeScript"
```typescript title="quick_sort.ts"
```
=== "C"
```c title="quick_sort.c"
```
=== "C#"
```csharp title="quick_sort.cs"
```

View file

@ -116,3 +116,33 @@ comments: true
""" 判断双向队列是否为空 """
is_empty = len(duque) == 0
```
=== "Go"
```go title="deque.go"
```
=== "JavaScript"
```js title="deque.js"
```
=== "TypeScript"
```typescript title="deque.ts"
```
=== "C"
```c title="deque.c"
```
=== "C#"
```csharp title="deque.cs"
```

View file

@ -112,6 +112,36 @@ comments: true
is_empty = len(que) == 0
```
=== "Go"
```go title="queue.go"
```
=== "JavaScript"
```js title="queue.js"
```
=== "TypeScript"
```typescript title="queue.ts"
```
=== "C"
```c title="queue.c"
```
=== "C#"
```csharp title="queue.cs"
```
## 队列实现
队列需要一种可以在一端添加,并在另一端删除的数据结构,也可以使用链表或数组来实现。
@ -276,6 +306,36 @@ comments: true
return self.__front.val
```
=== "Go"
```go title="linkedlist_queue.go"
```
=== "JavaScript"
```js title="linkedlist_queue.js"
```
=== "TypeScript"
```typescript title="linkedlist_queue.ts"
```
=== "C"
```c title="linkedlist_queue.c"
```
=== "C#"
```csharp title="linkedlist_queue.cs"
```
### 基于数组的实现
数组的删除首元素的时间复杂度为 $O(n)$ ,因此不适合直接用来实现队列。然而,我们可以借助两个指针 `front` , `rear` 来分别记录队首和队尾的索引位置,在入队 / 出队时分别将 `front` / `rear` 向后移动一位即可,这样每次仅需操作一个元素,时间复杂度降至 $O(1)$ 。
@ -477,6 +537,36 @@ comments: true
return res
```
=== "Go"
```go title="array_queue.go"
```
=== "JavaScript"
```js title="array_queue.js"
```
=== "TypeScript"
```typescript title="array_queue.ts"
```
=== "C"
```c title="array_queue.c"
```
=== "C#"
```csharp title="array_queue.cs"
```
## 队列典型应用
- **淘宝订单。** 购物者下单后,订单就被加入到队列之中,随后系统再根据顺序依次处理队列中的订单。在双十一时,在短时间内会产生海量的订单,如何处理「高并发」则是工程师们需要重点思考的问题。

View file

@ -112,6 +112,36 @@ comments: true
is_empty = len(stack) == 0
```
=== "Go"
```go title="stack.go"
```
=== "JavaScript"
```js title="stack.js"
```
=== "TypeScript"
```typescript title="stack.ts"
```
=== "C"
```c title="stack.c"
```
=== "C#"
```csharp title="stack.cs"
```
## 栈的实现
为了更加清晰地了解栈的运行机制,接下来我们来自己动手实现一个栈类。
@ -249,6 +279,36 @@ comments: true
return self.__peek.val
```
=== "Go"
```go title="linkedlist_stack.go"
```
=== "JavaScript"
```js title="linkedlist_stack.js"
```
=== "TypeScript"
```typescript title="linkedlist_stack.ts"
```
=== "C"
```c title="linkedlist_stack.c"
```
=== "C#"
```csharp title="linkedlist_stack.cs"
```
### 基于数组的实现
使用「数组」实现栈时,将数组的尾部当作栈顶。准确地说,我们需要使用「列表」,因为入栈的元素可能是源源不断的,因此使用动态数组可以方便扩容。
@ -363,6 +423,36 @@ comments: true
return self.__stack[index]
```
=== "Go"
```go title="array_stack.go"
```
=== "JavaScript"
```js title="array_stack.js"
```
=== "TypeScript"
```typescript title="array_stack.ts"
```
=== "C"
```c title="array_stack.c"
```
=== "C#"
```csharp title="array_stack.cs"
```
!!! tip
实际编程中,我们一般直接将 `ArrayList``LinkedList` 当作「栈」来使用。我们仅需通过脑补来屏蔽无关操作,而不用专门去包装它。

View file

@ -91,6 +91,30 @@ comments: true
```
=== "JavaScript"
```js title="binary_search_tree.js"
```
=== "TypeScript"
```typescript title="binary_search_tree.ts"
```
=== "C"
```c title="binary_search_tree.c"
```
=== "C#"
```csharp title="binary_search_tree.cs"
```
### 插入结点
给定一个待插入元素 `num` ,为了保持二叉搜索树 “左子树 < 根结点 < 右子树 的性质插入操作分为两步
@ -166,6 +190,30 @@ comments: true
```
=== "JavaScript"
```js title="binary_search_tree.js"
```
=== "TypeScript"
```typescript title="binary_search_tree.ts"
```
=== "C"
```c title="binary_search_tree.c"
```
=== "C#"
```csharp title="binary_search_tree.cs"
```
为了插入结点,需要借助 **辅助结点 `prev`** 保存上一轮循环的结点,这样在遍历到 $\text{null}$ 时,我们也可以获取到其父结点,从而完成结点插入操作。
与查找结点相同,插入结点使用 $O(\log n)$ 时间。
@ -320,6 +368,30 @@ comments: true
```
=== "JavaScript"
```js title="binary_search_tree.js"
```
=== "TypeScript"
```typescript title="binary_search_tree.ts"
```
=== "C"
```c title="binary_search_tree.c"
```
=== "C#"
```csharp title="binary_search_tree.cs"
```
## 二叉搜索树的优势
假设给定 $n$ 个数字,最常用的存储方式是「数组」,那么对于这串乱序的数字,常见操作的效率为:

View file

@ -8,7 +8,7 @@ comments: true
=== "Java"
```java
```java title=""
/* 链表结点类 */
class TreeNode {
int val; // 结点值
@ -20,7 +20,7 @@ comments: true
=== "C++"
```cpp
```cpp title=""
/* 链表结点结构体 */
struct TreeNode {
int val; // 结点值
@ -32,7 +32,7 @@ comments: true
=== "Python"
```python
```python title=""
""" 链表结点类 """
class TreeNode:
def __init__(self, val=0, left=None, right=None):
@ -43,7 +43,31 @@ comments: true
=== "Go"
```go
```go title=""
```
=== "JavaScript"
```js title=""
```
=== "TypeScript"
```typescript title=""
```
=== "C"
```c title=""
```
=== "C#"
```csharp title=""
```
@ -142,6 +166,30 @@ comments: true
```
=== "JavaScript"
```js title="binary_tree.js"
```
=== "TypeScript"
```typescript title="binary_tree.ts"
```
=== "C"
```c title="binary_tree.c"
```
=== "C#"
```csharp title="binary_tree.cs"
```
**插入与删除结点。** 与链表类似,插入与删除结点都可以通过修改指针实现。
![binary_tree_add_remove](binary_tree.assets/binary_tree_add_remove.png)
@ -183,6 +231,30 @@ comments: true
```
=== "JavaScript"
```js title="binary_tree.js"
```
=== "TypeScript"
```typescript title="binary_tree.ts"
```
=== "C"
```c title="binary_tree.c"
```
=== "C#"
```csharp title="binary_tree.cs"
```
!!! note
插入结点会改变二叉树的原有逻辑结构,删除结点往往意味着删除了该结点的所有子树。因此,二叉树中的插入与删除一般都是由一套操作配合完成的,这样才能实现有意义的操作。
@ -259,6 +331,30 @@ comments: true
```
=== "JavaScript"
```js title="binary_tree_bfs.js"
```
=== "TypeScript"
```typescript title="binary_tree_bfs.ts"
```
=== "C"
```c title="binary_tree_bfs.c"
```
=== "C#"
```csharp title="binary_tree_bfs.cs"
```
### 前序、中序、后序遍历
相对地,前、中、后序遍历皆属于「深度优先遍历 Depth-First Traversal」其体现着一种 “先走到尽头,再回头继续” 的回溯遍历方式。
@ -353,6 +449,30 @@ comments: true
```
=== "JavaScript"
```js title="binary_tree_dfs.js"
```
=== "TypeScript"
```typescript title="binary_tree_dfs.ts"
```
=== "C"
```c title="binary_tree_dfs.c"
```
=== "C#"
```csharp title="binary_tree_dfs.cs"
```
!!! note
使用循环一样可以实现前、中、后序遍历,但代码相对繁琐,有兴趣的同学可以自行实现。

View file

@ -16,7 +16,8 @@ comments: true
完美二叉树的性质有:
- 若树高度 $= h$ ,则结点总数 $= 2^h$ - 1
- 若树高度 $= h$ ,则结点总数 $= 2^h - 1$
- TODO
## 完全二叉树
@ -26,7 +27,7 @@ comments: true
完全二叉树有一个很好的性质,可以用「数组」来表示。
-
- TODO
## 完满二叉树
@ -39,3 +40,5 @@ comments: true
**「平衡二叉树 Balanced Binary Tree」又称「AVL 树」** ,其任意结点的左子树和右子树的高度之差的绝对值 $\leq 1$ 。
![balanced_binary_tree](binary_tree_types.assets/balanced_binary_tree.png)
- TODO