This commit is contained in:
krahets 2023-11-27 02:32:06 +08:00
parent 32d5bd97aa
commit a4a23e2488
31 changed files with 179 additions and 213 deletions

View File

@ -39,7 +39,7 @@ comments: true
### 7.   C# 环境
1. 下载并安装 [.Net 6.0](https://dotnet.microsoft.com/en-us/download) 。
1. 下载并安装 [.Net 8.0](https://dotnet.microsoft.com/en-us/download) 。
2. 在 VSCode 的插件市场中搜索 `C# Dev Kit` ,安装 C# Dev Kit [配置教程](https://code.visualstudio.com/docs/csharp/get-started))。
3. 也可使用 Visual Studio[安装教程](https://learn.microsoft.com/zh-cn/visualstudio/install/install-visual-studio?view=vs-2022))。

View File

@ -49,7 +49,7 @@ comments: true
```csharp title="array.cs"
/* 初始化数组 */
int[] arr = new int[5]; // { 0, 0, 0, 0, 0 }
int[] nums = { 1, 3, 2, 5, 4 };
int[] nums = [1, 3, 2, 5, 4];
```
=== "Go"

View File

@ -58,10 +58,9 @@ comments: true
```csharp title=""
/* 链表节点类 */
class ListNode {
int val; // 节点值
ListNode next; // 指向下一节点的引用
ListNode(int x) => val = x; //构造函数
class ListNode(int x) { //构造函数
int val = x; // 节点值
ListNode? next; // 指向下一节点的引用
}
```
@ -774,7 +773,7 @@ comments: true
```csharp title="linked_list.cs"
/* 访问链表中索引为 index 的节点 */
ListNode? Access(ListNode head, int index) {
ListNode? Access(ListNode? head, int index) {
for (int i = 0; i < index; i++) {
if (head == null)
return null;
@ -953,7 +952,7 @@ comments: true
```csharp title="linked_list.cs"
/* 在链表中查找值为 target 的首个节点 */
int Find(ListNode head, int target) {
int Find(ListNode? head, int target) {
int index = 0;
while (head != null) {
if (head.val == target)
@ -1162,11 +1161,10 @@ comments: true
```csharp title=""
/* 双向链表节点类 */
class ListNode {
int val; // 节点值
class ListNode(int x) { // 构造函数
int val = x; // 节点值
ListNode next; // 指向后继节点的引用
ListNode prev; // 指向前驱节点的引用
ListNode(int x) => val = x; // 构造函数
}
```

View File

@ -58,10 +58,10 @@ comments: true
```csharp title="list.cs"
/* 初始化列表 */
// 无初始值
List<int> nums1 = new();
List<int> nums1 = [];
// 有初始值
int[] numbers = new int[] { 1, 3, 2, 5, 4 };
List<int> nums = numbers.ToList();
int[] numbers = [1, 3, 2, 5, 4];
List<int> nums = [.. numbers];
```
=== "Go"
@ -704,7 +704,7 @@ comments: true
```csharp title="list.cs"
/* 拼接两个列表 */
List<int> nums1 = new() { 6, 8, 7, 10, 9 };
List<int> nums1 = [6, 8, 7, 10, 9];
nums.AddRange(nums1); // 将列表 nums1 拼接到 nums 之后
```

View File

@ -66,7 +66,7 @@ comments: true
```csharp title="preorder_traversal_i_compact.cs"
/* 前序遍历:例题一 */
void PreOrder(TreeNode root) {
void PreOrder(TreeNode? root) {
if (root == null) {
return;
}
@ -288,7 +288,7 @@ comments: true
```csharp title="preorder_traversal_ii_compact.cs"
/* 前序遍历:例题二 */
void PreOrder(TreeNode root) {
void PreOrder(TreeNode? root) {
if (root == null) {
return;
}
@ -588,7 +588,7 @@ comments: true
```csharp title="preorder_traversal_iii_compact.cs"
/* 前序遍历:例题三 */
void PreOrder(TreeNode root) {
void PreOrder(TreeNode? root) {
// 剪枝
if (root == null || root.val == 3) {
return;
@ -1267,7 +1267,7 @@ comments: true
// 尝试:做出选择,更新状态
MakeChoice(state, choice);
// 进行下一轮选择
Backtrack(state, new List<TreeNode> { choice.left, choice.right }, res);
Backtrack(state, [choice.left!, choice.right!], res);
// 回退:撤销选择,恢复到之前的状态
UndoChoice(state, choice);
}

View File

@ -207,7 +207,7 @@ comments: true
bool[] cols, bool[] diags1, bool[] diags2) {
// 当放置完所有行时,记录解
if (row == n) {
List<List<string>> copyState = new();
List<List<string>> copyState = [];
foreach (List<string> sRow in state) {
copyState.Add(new List<string>(sRow));
}
@ -236,9 +236,9 @@ comments: true
/* 求解 N 皇后 */
List<List<List<string>>> NQueens(int n) {
// 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
List<List<string>> state = new();
List<List<string>> state = [];
for (int i = 0; i < n; i++) {
List<string> row = new();
List<string> row = [];
for (int j = 0; j < n; j++) {
row.Add("#");
}
@ -247,7 +247,7 @@ comments: true
bool[] cols = new bool[n]; // 记录列是否有皇后
bool[] diags1 = new bool[2 * n - 1]; // 记录主对角线是否有皇后
bool[] diags2 = new bool[2 * n - 1]; // 记录副对角线是否有皇后
List<List<List<string>>> res = new();
List<List<List<string>>> res = [];
Backtrack(0, n, state, res, cols, diags1, diags2);

View File

@ -187,8 +187,8 @@ comments: true
/* 全排列 I */
List<List<int>> PermutationsI(int[] nums) {
List<List<int>> res = new();
Backtrack(new List<int>(), nums, new bool[nums.Length], res);
List<List<int>> res = [];
Backtrack([], nums, new bool[nums.Length], res);
return res;
}
```
@ -623,7 +623,7 @@ comments: true
return;
}
// 遍历所有选择
ISet<int> duplicated = new HashSet<int>();
HashSet<int> duplicated = [];
for (int i = 0; i < choices.Length; i++) {
int choice = choices[i];
// 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
@ -643,8 +643,8 @@ comments: true
/* 全排列 II */
List<List<int>> PermutationsII(int[] nums) {
List<List<int>> res = new();
Backtrack(new List<int>(), nums, new bool[nums.Length], res);
List<List<int>> res = [];
Backtrack([], nums, new bool[nums.Length], res);
return res;
}
```

View File

@ -154,9 +154,9 @@ comments: true
/* 求解子集和 I包含重复子集 */
List<List<int>> SubsetSumINaive(int[] nums, int target) {
List<int> state = new(); // 状态(子集)
List<int> state = []; // 状态(子集)
int total = 0; // 子集和
List<List<int>> res = new(); // 结果列表(子集列表)
List<List<int>> res = []; // 结果列表(子集列表)
Backtrack(state, target, total, nums, res);
return res;
}
@ -609,10 +609,10 @@ comments: true
/* 求解子集和 I */
List<List<int>> SubsetSumI(int[] nums, int target) {
List<int> state = new(); // 状态(子集)
List<int> state = []; // 状态(子集)
Array.Sort(nums); // 对 nums 进行排序
int start = 0; // 遍历起始点
List<List<int>> res = new(); // 结果列表(子集列表)
List<List<int>> res = []; // 结果列表(子集列表)
Backtrack(state, target, nums, start, res);
return res;
}
@ -1093,10 +1093,10 @@ comments: true
/* 求解子集和 II */
List<List<int>> SubsetSumII(int[] nums, int target) {
List<int> state = new(); // 状态(子集)
List<int> state = []; // 状态(子集)
Array.Sort(nums); // 对 nums 进行排序
int start = 0; // 遍历起始点
List<List<int>> res = new(); // 结果列表(子集列表)
List<List<int>> res = []; // 结果列表(子集列表)
Backtrack(state, target, nums, start, res);
return res;
}

View File

@ -104,10 +104,9 @@ comments: true
```csharp title=""
/* 类 */
class Node {
int val;
class Node(int x) {
int val = x;
Node next;
Node(int x) { val = x; }
}
/* 函数 */
@ -119,7 +118,7 @@ comments: true
int Algorithm(int n) { // 输入数据
const int a = 0; // 暂存数据(常量)
int b = 0; // 暂存数据(变量)
Node node = new(0); // 暂存数据(对象)
Node node = new(0); // 暂存数据(对象)
int c = Function(); // 栈帧空间(调用函数)
return a + b + c; // 输出数据
}
@ -1123,12 +1122,12 @@ $$
// 长度为 n 的数组占用 O(n) 空间
int[] nums = new int[n];
// 长度为 n 的列表占用 O(n) 空间
List<ListNode> nodes = new();
List<ListNode> nodes = [];
for (int i = 0; i < n; i++) {
nodes.Add(new ListNode(i));
}
// 长度为 n 的哈希表占用 O(n) 空间
Dictionary<int, string> map = new();
Dictionary<int, string> map = [];
for (int i = 0; i < n; i++) {
map.Add(i, i.ToString());
}
@ -1524,9 +1523,9 @@ $$
// 矩阵占用 O(n^2) 空间
int[,] numMatrix = new int[n, n];
// 二维列表占用 O(n^2) 空间
List<List<int>> numList = new();
List<List<int>> numList = [];
for (int i = 0; i < n; i++) {
List<int> tmp = new();
List<int> tmp = [];
for (int j = 0; j < n; j++) {
tmp.Add(0);
}

View File

@ -2338,7 +2338,7 @@ $$
int Logarithmic(float n) {
int count = 0;
while (n > 1) {
n = n / 2;
n /= 2;
count++;
}
return count;

View File

@ -172,7 +172,7 @@ comments: true
```csharp title="build_tree.cs"
/* 构建二叉树:分治 */
TreeNode DFS(int[] preorder, Dictionary<int, int> inorderMap, int i, int l, int r) {
TreeNode? DFS(int[] preorder, Dictionary<int, int> inorderMap, int i, int l, int r) {
// 子树区间为空时终止
if (r - l < 0)
return null;
@ -189,13 +189,13 @@ comments: true
}
/* 构建二叉树 */
TreeNode BuildTree(int[] preorder, int[] inorder) {
TreeNode? BuildTree(int[] preorder, int[] inorder) {
// 初始化哈希表,存储 inorder 元素到索引的映射
Dictionary<int, int> inorderMap = new();
Dictionary<int, int> inorderMap = [];
for (int i = 0; i < inorder.Length; i++) {
inorderMap.TryAdd(inorder[i], i);
}
TreeNode root = DFS(preorder, inorderMap, 0, 0, inorder.Length - 1);
TreeNode? root = DFS(preorder, inorderMap, 0, 0, inorder.Length - 1);
return root;
}
```

View File

@ -126,9 +126,9 @@ comments: true
/* 爬楼梯:回溯 */
int ClimbingStairsBacktrack(int n) {
List<int> choices = new() { 1, 2 }; // 可选择向上爬 1 或 2 阶
List<int> choices = [1, 2]; // 可选择向上爬 1 或 2 阶
int state = 0; // 从第 0 阶开始爬
List<int> res = new() { 0 }; // 使用 res[0] 记录方案数量
List<int> res = [0]; // 使用 res[0] 记录方案数量
Backtrack(choices, state, n, res);
return res[0];
}

View File

@ -291,13 +291,13 @@ comments: true
```csharp title="graph_adjacency_matrix.cs"
/* 基于邻接矩阵实现的无向图类 */
class GraphAdjMat {
readonly List<int> vertices; // 顶点列表,元素代表“顶点值”,索引代表“顶点索引”
readonly List<List<int>> adjMat; // 邻接矩阵,行列索引对应“顶点索引”
List<int> vertices; // 顶点列表,元素代表“顶点值”,索引代表“顶点索引”
List<List<int>> adjMat; // 邻接矩阵,行列索引对应“顶点索引”
/* 构造函数 */
public GraphAdjMat(int[] vertices, int[][] edges) {
this.vertices = new List<int>();
this.adjMat = new List<List<int>>();
this.vertices = [];
this.adjMat = [];
// 添加顶点
foreach (int val in vertices) {
AddVertex(val);
@ -310,7 +310,7 @@ comments: true
}
/* 获取顶点数量 */
public int Size() {
int Size() {
return vertices.Count;
}
@ -1311,7 +1311,7 @@ comments: true
/* 构造函数 */
public GraphAdjList(Vertex[][] edges) {
this.adjList = new Dictionary<Vertex, List<Vertex>>();
adjList = [];
// 添加所有顶点和边
foreach (Vertex[] edge in edges) {
AddVertex(edge[0]);
@ -1321,7 +1321,7 @@ comments: true
}
/* 获取顶点数量 */
public int Size() {
int Size() {
return adjList.Count;
}
@ -1348,7 +1348,7 @@ comments: true
if (adjList.ContainsKey(vet))
return;
// 在邻接表中添加一个新链表
adjList.Add(vet, new List<Vertex>());
adjList.Add(vet, []);
}
/* 删除顶点 */
@ -1367,7 +1367,7 @@ comments: true
public void Print() {
Console.WriteLine("邻接表 =");
foreach (KeyValuePair<Vertex, List<Vertex>> pair in adjList) {
List<int> tmp = new();
List<int> tmp = [];
foreach (Vertex vertex in pair.Value)
tmp.Add(vertex.val);
Console.WriteLine(pair.Key.val + ": [" + string.Join(", ", tmp) + "],");

View File

@ -121,9 +121,9 @@ BFS 通常借助队列来实现。队列具有“先入先出”的性质,这
// 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点
List<Vertex> GraphBFS(GraphAdjList graph, Vertex startVet) {
// 顶点遍历序列
List<Vertex> res = new();
List<Vertex> res = [];
// 哈希表,用于记录已被访问过的顶点
HashSet<Vertex> visited = new() { startVet };
HashSet<Vertex> visited = [startVet];
// 队列用于实现 BFS
Queue<Vertex> que = new();
que.Enqueue(startVet);
@ -579,9 +579,9 @@ BFS 通常借助队列来实现。队列具有“先入先出”的性质,这
// 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点
List<Vertex> GraphDFS(GraphAdjList graph, Vertex startVet) {
// 顶点遍历序列
List<Vertex> res = new();
List<Vertex> res = [];
// 哈希表,用于记录已被访问过的顶点
HashSet<Vertex> visited = new();
HashSet<Vertex> visited = [];
DFS(graph, visited, res, startVet);
return res;
}

View File

@ -155,14 +155,9 @@ comments: true
```csharp title="fractional_knapsack.cs"
/* 物品 */
class Item {
public int w; // 物品重量
public int v; // 物品价值
public Item(int w, int v) {
this.w = w;
this.v = v;
}
class Item(int w, int v) {
public int w = w; // 物品重量
public int v = v; // 物品价值
}
/* 分数背包:贪心 */

View File

@ -731,7 +731,7 @@ $$
int hashStr = str.GetHashCode();
// 字符串 Hello 算法 的哈希值为 -586107568;
object[] arr = { 12836, "小哈" };
object[] arr = [12836, "小哈"];
int hashTup = arr.GetHashCode();
// 数组 [12836, 小哈] 的哈希值为 42931033;

View File

@ -359,8 +359,8 @@ comments: true
class HashMapChaining {
int size; // 键值对数量
int capacity; // 哈希表容量
readonly double loadThres; // 触发扩容的负载因子阈值
readonly int extendRatio; // 扩容倍数
double loadThres; // 触发扩容的负载因子阈值
int extendRatio; // 扩容倍数
List<List<Pair>> buckets; // 桶数组
/* 构造方法 */
@ -371,17 +371,17 @@ comments: true
extendRatio = 2;
buckets = new List<List<Pair>>(capacity);
for (int i = 0; i < capacity; i++) {
buckets.Add(new List<Pair>());
buckets.Add([]);
}
}
/* 哈希函数 */
private int HashFunc(int key) {
int HashFunc(int key) {
return key % capacity;
}
/* 负载因子 */
private double LoadFactor() {
double LoadFactor() {
return (double)size / capacity;
}
@ -431,14 +431,14 @@ comments: true
}
/* 扩容哈希表 */
private void Extend() {
void Extend() {
// 暂存原哈希表
List<List<Pair>> bucketsTmp = buckets;
// 初始化扩容后的新哈希表
capacity *= extendRatio;
buckets = new List<List<Pair>>(capacity);
for (int i = 0; i < capacity; i++) {
buckets.Add(new List<Pair>());
buckets.Add([]);
}
size = 0;
// 将键值对从原哈希表搬运至新哈希表
@ -452,7 +452,7 @@ comments: true
/* 打印哈希表 */
public void Print() {
foreach (List<Pair> bucket in buckets) {
List<string> res = new();
List<string> res = [];
foreach (Pair pair in bucket) {
res.Add(pair.key + " -> " + pair.val);
}
@ -1727,12 +1727,12 @@ comments: true
```csharp title="hash_map_open_addressing.cs"
/* 开放寻址哈希表 */
class HashMapOpenAddressing {
private int size; // 键值对数量
private int capacity = 4; // 哈希表容量
private readonly double loadThres = 2.0 / 3.0; // 触发扩容的负载因子阈值
private readonly int extendRatio = 2; // 扩容倍数
private Pair[] buckets; // 桶数组
private readonly Pair TOMBSTONE = new(-1, "-1"); // 删除标记
int size; // 键值对数量
int capacity = 4; // 哈希表容量
double loadThres = 2.0 / 3.0; // 触发扩容的负载因子阈值
int extendRatio = 2; // 扩容倍数
Pair[] buckets; // 桶数组
Pair TOMBSTONE = new(-1, "-1"); // 删除标记
/* 构造方法 */
public HashMapOpenAddressing() {
@ -1741,17 +1741,17 @@ comments: true
}
/* 哈希函数 */
private int HashFunc(int key) {
int HashFunc(int key) {
return key % capacity;
}
/* 负载因子 */
private double LoadFactor() {
double LoadFactor() {
return (double)size / capacity;
}
/* 搜索 key 对应的桶索引 */
private int FindBucket(int key) {
int FindBucket(int key) {
int index = HashFunc(key);
int firstTombstone = -1;
// 线性探测,当遇到空桶时跳出
@ -1819,7 +1819,7 @@ comments: true
}
/* 扩容哈希表 */
private void Extend() {
void Extend() {
// 暂存原哈希表
Pair[] bucketsTmp = buckets;
// 初始化扩容后的新哈希表

View File

@ -776,28 +776,24 @@ index = hash(key) % capacity
```csharp title="array_hash_map.cs"
/* 键值对 int->string */
class Pair {
public int key;
public string val;
public Pair(int key, string val) {
this.key = key;
this.val = val;
}
class Pair(int key, string val) {
public int key = key;
public string val = val;
}
/* 基于数组简易实现的哈希表 */
class ArrayHashMap {
private readonly List<Pair?> buckets;
List<Pair?> buckets;
public ArrayHashMap() {
// 初始化数组,包含 100 个桶
buckets = new();
buckets = [];
for (int i = 0; i < 100; i++) {
buckets.Add(null);
}
}
/* 哈希函数 */
private int HashFunc(int key) {
int HashFunc(int key) {
int index = key % 100;
return index;
}
@ -826,7 +822,7 @@ index = hash(key) % capacity
/* 获取所有键值对 */
public List<Pair> PairSet() {
List<Pair> pairSet = new();
List<Pair> pairSet = [];
foreach (Pair? pair in buckets) {
if (pair != null)
pairSet.Add(pair);
@ -836,7 +832,7 @@ index = hash(key) % capacity
/* 获取所有键 */
public List<int> KeySet() {
List<int> keySet = new();
List<int> keySet = [];
foreach (Pair? pair in buckets) {
if (pair != null)
keySet.Add(pair.key);
@ -846,7 +842,7 @@ index = hash(key) % capacity
/* 获取所有值 */
public List<string> ValueSet() {
List<string> valueSet = new();
List<string> valueSet = [];
foreach (Pair? pair in buckets) {
if (pair != null)
valueSet.Add(pair.val);
@ -1462,7 +1458,7 @@ index = hash(key) % capacity
for (i = 0; i < HASHTABLE_CAPACITY; i++) {
if (hmap->buckets[i] != NULL) {
entries[index].key = hmap->buckets[i]->key;
entries[index].val = malloc(strlen(hmap->buckets[i]->val + 1));
entries[index].val = malloc(strlen(hmap->buckets[i]->val) + 1);
strcpy(entries[index].val, hmap->buckets[i]->val);
index++;
}

View File

@ -197,7 +197,7 @@ comments: true
bool isEmpty = maxHeap.Count == 0;
/* 输入列表并建堆 */
minHeap = new PriorityQueue<int, int>(new List<(int, int)> { (1, 1), (3, 3), (2, 2), (5, 5), (4, 4), });
minHeap = new PriorityQueue<int, int>([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]);
```
=== "Go"

View File

@ -75,10 +75,10 @@ comments: true
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 [i, j];
}
}
return Array.Empty<int>();
return [];
}
```
@ -309,15 +309,15 @@ comments: true
int[] TwoSumHashTable(int[] nums, int target) {
int size = nums.Length;
// 辅助哈希表,空间复杂度 O(n)
Dictionary<int, int> dic = new();
Dictionary<int, int> dic = [];
// 单层循环,时间复杂度 O(n)
for (int i = 0; i < size; i++) {
if (dic.ContainsKey(target - nums[i])) {
return new int[] { dic[target - nums[i]], i };
return [dic[target - nums[i]], i];
}
dic.Add(nums[i], i);
}
return Array.Empty<int>();
return [];
}
```

View File

@ -116,9 +116,9 @@ comments: true
void BucketSort(float[] nums) {
// 初始化 k = n/2 个桶,预期向每个桶分配 2 个元素
int k = nums.Length / 2;
List<List<float>> buckets = new();
List<List<float>> buckets = [];
for (int i = 0; i < k; i++) {
buckets.Add(new List<float>());
buckets.Add([]);
}
// 1. 将数组元素分配到各个桶中
foreach (float num in nums) {

View File

@ -297,7 +297,7 @@ comments: true
}
// 2. 统计各数字的出现次数
// counter[num] 代表 num 的出现次数
int *counter = malloc(sizeof(int) * m);
int *counter = calloc(m, sizeof(int));
for (int i = 0; i < size; i++) {
counter[nums[i]]++;
}
@ -308,6 +308,8 @@ comments: true
nums[i] = num;
}
}
// 4. 释放内存
free(counter);
}
```
@ -744,7 +746,7 @@ $$
}
// 2. 统计各数字的出现次数
// counter[num] 代表 num 的出现次数
int *counter = malloc(sizeof(int) * m);
int *counter = calloc(m, sizeof(int));
for (int i = 0; i < size; i++) {
counter[nums[i]]++;
}
@ -763,6 +765,8 @@ $$
}
// 使用结果数组 res 覆盖原数组 nums
memcpy(nums, res, size * sizeof(int));
// 5. 释放内存
free(counter);
}
```

View File

@ -985,20 +985,7 @@ comments: true
return right;
}
/* 快速排序类(中位基准数优化) */
// 选取三个元素的中位数
int medianThree(int nums[], int left, int mid, int 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;
}
// 哨兵划分(三数取中值)
/* 哨兵划分(三数取中值) */
int partitionMedian(int nums[], int left, int right) {
// 选取三个候选元素的中位数
int med = medianThree(nums, left, (left + right) / 2, right);

View File

@ -777,22 +777,16 @@ comments: true
```csharp title="linkedlist_deque.cs"
/* 双向链表节点 */
class ListNode {
public int val; // 节点值
public ListNode? next; // 后继节点引用
public ListNode? prev; // 前驱节点引用
public ListNode(int val) {
this.val = val;
prev = null;
next = null;
}
class ListNode(int val) {
public int val = val; // 节点值
public ListNode? next = null; // 后继节点引用
public ListNode? prev = null; // 前驱节点引用
}
/* 基于双向链表实现的双向队列 */
class LinkedListDeque {
private ListNode? front, rear; // 头节点 front, 尾节点 rear
private int queSize = 0; // 双向队列的长度
ListNode? front, rear; // 头节点 front, 尾节点 rear
int queSize = 0; // 双向队列的长度
public LinkedListDeque() {
front = null;
@ -810,7 +804,7 @@ comments: true
}
/* 入队操作 */
private void Push(int num, bool isFront) {
void Push(int num, bool isFront) {
ListNode node = new(num);
// 若链表为空,则令 front, rear 都指向 node
if (IsEmpty()) {
@ -820,14 +814,14 @@ comments: true
// 队首入队操作
else if (isFront) {
// 将 node 添加至链表头部
front.prev = node;
front!.prev = node;
node.next = front;
front = node; // 更新头节点
}
// 队尾入队操作
else {
// 将 node 添加至链表尾部
rear.next = node;
rear!.next = node;
node.prev = rear;
rear = node; // 更新尾节点
}
@ -846,7 +840,7 @@ comments: true
}
/* 出队操作 */
private int? Pop(bool isFront) {
int? Pop(bool isFront) {
if (IsEmpty())
throw new Exception();
int? val;
@ -857,7 +851,7 @@ comments: true
ListNode? fNext = front?.next;
if (fNext != null) {
fNext.prev = null;
front.next = null;
front!.next = null;
}
front = fNext; // 更新头节点
}
@ -868,7 +862,7 @@ comments: true
ListNode? rPrev = rear?.prev;
if (rPrev != null) {
rPrev.next = null;
rear.prev = null;
rear!.prev = null;
}
rear = rPrev; // 更新尾节点
}
@ -2343,18 +2337,18 @@ comments: true
```csharp title="array_deque.cs"
/* 基于环形数组实现的双向队列 */
class ArrayDeque {
private readonly int[] nums; // 用于存储双向队列元素的数组
private int front; // 队首指针,指向队首元素
private int queSize; // 双向队列长度
int[] nums; // 用于存储双向队列元素的数组
int front; // 队首指针,指向队首元素
int queSize; // 双向队列长度
/* 构造方法 */
public ArrayDeque(int capacity) {
this.nums = new int[capacity];
nums = new int[capacity];
front = queSize = 0;
}
/* 获取双向队列的容量 */
public int Capacity() {
int Capacity() {
return nums.Length;
}
@ -2369,7 +2363,7 @@ comments: true
}
/* 计算环形数组索引 */
private int Index(int i) {
int Index(int i) {
// 通过取余操作实现数组首尾相连
// 当 i 越过数组尾部后,回到头部
// 当 i 越过数组头部后,回到尾部

View File

@ -547,8 +547,8 @@ comments: true
```csharp title="linkedlist_queue.cs"
/* 基于链表实现的队列 */
class LinkedListQueue {
private ListNode? front, rear; // 头节点 front ,尾节点 rear
private int queSize = 0;
ListNode? front, rear; // 头节点 front ,尾节点 rear
int queSize = 0;
public LinkedListQueue() {
front = null;
@ -594,18 +594,18 @@ comments: true
public int Peek() {
if (IsEmpty())
throw new Exception();
return front.val;
return front!.val;
}
/* 将链表转化为 Array 并返回 */
public int[] ToArray() {
if (front == null)
return Array.Empty<int>();
return [];
ListNode node = front;
ListNode? node = front;
int[] res = new int[Size()];
for (int i = 0; i < res.Length; i++) {
res[i] = node.val;
res[i] = node!.val;
node = node.next;
}
return res;
@ -1445,9 +1445,9 @@ comments: true
```csharp title="array_queue.cs"
/* 基于环形数组实现的队列 */
class ArrayQueue {
private readonly int[] nums; // 用于存储队列元素的数组
private int front; // 队首指针,指向队首元素
private int queSize; // 队列长度
int[] nums; // 用于存储队列元素的数组
int front; // 队首指针,指向队首元素
int queSize; // 队列长度
public ArrayQueue(int capacity) {
nums = new int[capacity];
@ -1455,7 +1455,7 @@ comments: true
}
/* 获取队列的容量 */
public int Capacity() {
int Capacity() {
return nums.Length;
}

View File

@ -518,8 +518,8 @@ comments: true
```csharp title="linkedlist_stack.cs"
/* 基于链表实现的栈 */
class LinkedListStack {
private ListNode? stackPeek; // 将头节点作为栈顶
private int stkSize = 0; // 栈的长度
ListNode? stackPeek; // 将头节点作为栈顶
int stkSize = 0; // 栈的长度
public LinkedListStack() {
stackPeek = null;
@ -547,7 +547,7 @@ comments: true
/* 出栈 */
public int Pop() {
int num = Peek();
stackPeek = stackPeek.next;
stackPeek = stackPeek!.next;
stkSize--;
return num;
}
@ -556,18 +556,18 @@ comments: true
public int Peek() {
if (IsEmpty())
throw new Exception();
return stackPeek.val;
return stackPeek!.val;
}
/* 将 List 转化为 Array 并返回 */
public int[] ToArray() {
if (stackPeek == null)
return Array.Empty<int>();
return [];
ListNode node = stackPeek;
ListNode? node = stackPeek;
int[] res = new int[Size()];
for (int i = res.Length - 1; i >= 0; i--) {
res[i] = node.val;
res[i] = node!.val;
node = node.next;
}
return res;
@ -1237,10 +1237,10 @@ comments: true
```csharp title="array_stack.cs"
/* 基于数组实现的栈 */
class ArrayStack {
private readonly List<int> stack;
List<int> stack;
public ArrayStack() {
// 初始化列表(动态数组)
stack = new();
stack = [];
}
/* 获取栈的长度 */
@ -1276,7 +1276,7 @@ comments: true
/* 将 List 转化为 Array 并返回 */
public int[] ToArray() {
return stack.ToArray();
return [.. stack];
}
}
```

View File

@ -61,7 +61,7 @@ comments: true
```csharp title=""
/* 二叉树的数组表示 */
// 使用 int? 可空类型 ,就可以使用 null 来标记空位
int?[] tree = { 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 };
int?[] tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15];
```
=== "Go"
@ -410,13 +410,8 @@ comments: true
```csharp title="array_binary_tree.cs"
/* 数组表示下的二叉树类 */
class ArrayBinaryTree {
private readonly List<int?> tree;
/* 构造方法 */
public ArrayBinaryTree(List<int?> arr) {
tree = new List<int?>(arr);
}
class ArrayBinaryTree(List<int?> arr) {
List<int?> tree = new(arr);
/* 节点数量 */
public int Size() {
@ -448,50 +443,50 @@ comments: true
/* 层序遍历 */
public List<int> LevelOrder() {
List<int> res = new();
List<int> res = [];
// 直接遍历数组
for (int i = 0; i < Size(); i++) {
if (Val(i).HasValue)
res.Add(Val(i).Value);
res.Add(Val(i)!.Value);
}
return res;
}
/* 深度优先遍历 */
private void DFS(int i, string order, List<int> res) {
void DFS(int i, string order, List<int> res) {
// 若为空位,则返回
if (!Val(i).HasValue)
return;
// 前序遍历
if (order == "pre")
res.Add(Val(i).Value);
res.Add(Val(i)!.Value);
DFS(Left(i), order, res);
// 中序遍历
if (order == "in")
res.Add(Val(i).Value);
res.Add(Val(i)!.Value);
DFS(Right(i), order, res);
// 后序遍历
if (order == "post")
res.Add(Val(i).Value);
res.Add(Val(i)!.Value);
}
/* 前序遍历 */
public List<int> PreOrder() {
List<int> res = new();
List<int> res = [];
DFS(0, "pre", res);
return res;
}
/* 中序遍历 */
public List<int> InOrder() {
List<int> res = new();
List<int> res = [];
DFS(0, "in", res);
return res;
}
/* 后序遍历 */
public List<int> PostOrder() {
List<int> res = new();
List<int> res = [];
DFS(0, "post", res);
return res;
}

View File

@ -71,12 +71,11 @@ AVL 树既是二叉搜索树也是平衡二叉树,同时满足这两类二叉
```csharp title=""
/* AVL 树节点类 */
class TreeNode {
public int val; // 节点值
public int height; // 节点高度
public TreeNode? left; // 左子节点
public TreeNode? right; // 右子节点
public TreeNode(int x) { val = x; }
class TreeNode(int? x) {
public int? val = x; // 节点值
public int height; // 节点高度
public TreeNode? left; // 左子节点引用
public TreeNode? right; // 右子节点引用
}
```
@ -689,7 +688,7 @@ AVL 树的特点在于“旋转”操作,它能够在不影响二叉树的中
```csharp title="avl_tree.cs"
/* 右旋操作 */
TreeNode? RightRotate(TreeNode? node) {
TreeNode? child = node.left;
TreeNode? child = node?.left;
TreeNode? grandChild = child?.right;
// 以 child 为原点,将 node 向右旋转
child.right = node;
@ -926,7 +925,7 @@ AVL 树的特点在于“旋转”操作,它能够在不影响二叉树的中
```csharp title="avl_tree.cs"
/* 左旋操作 */
TreeNode? LeftRotate(TreeNode? node) {
TreeNode? child = node.right;
TreeNode? child = node?.right;
TreeNode? grandChild = child?.left;
// 以 child 为原点,将 node 向左旋转
child.left = node;
@ -1236,23 +1235,23 @@ AVL 树的特点在于“旋转”操作,它能够在不影响二叉树的中
int balanceFactorInt = BalanceFactor(node);
// 左偏树
if (balanceFactorInt > 1) {
if (BalanceFactor(node.left) >= 0) {
if (BalanceFactor(node?.left) >= 0) {
// 右旋
return RightRotate(node);
} else {
// 先左旋后右旋
node.left = LeftRotate(node?.left);
node!.left = LeftRotate(node!.left);
return RightRotate(node);
}
}
// 右偏树
if (balanceFactorInt < -1) {
if (BalanceFactor(node.right) <= 0) {
if (BalanceFactor(node?.right) <= 0) {
// 左旋
return LeftRotate(node);
} else {
// 先右旋后左旋
node.right = RightRotate(node?.right);
node!.right = RightRotate(node!.right);
return LeftRotate(node);
}
}
@ -2059,7 +2058,7 @@ AVL 树的节点插入操作与二叉搜索树在主体上类似。唯一的区
while (temp.left != null) {
temp = temp.left;
}
node.right = RemoveHelper(node.right, temp.val);
node.right = RemoveHelper(node.right, temp.val!.Value);
node.val = temp.val;
}
}

View File

@ -980,7 +980,7 @@ comments: true
TreeNode? child = cur.left ?? cur.right;
// 删除节点 cur
if (cur != root) {
if (pre.left == cur)
if (pre!.left == cur)
pre.left = child;
else
pre.right = child;
@ -997,7 +997,7 @@ comments: true
tmp = tmp.left;
}
// 递归删除节点 tmp
Remove(tmp.val);
Remove(tmp.val!.Value);
// 用 tmp 覆盖 cur
cur.val = tmp.val;
}

View File

@ -45,11 +45,10 @@ comments: true
```csharp title=""
/* 二叉树节点类 */
class TreeNode {
int val; // 节点值
TreeNode? left; // 左子节点引用
TreeNode? right; // 右子节点引用
TreeNode(int x) { val = x; }
class TreeNode(int? x) {
public int? val = x; // 节点值
public TreeNode? left; // 左子节点引用
public TreeNode? right; // 右子节点引用
}
```

View File

@ -96,10 +96,10 @@ comments: true
Queue<TreeNode> queue = new();
queue.Enqueue(root);
// 初始化一个列表,用于保存遍历序列
List<int> list = new();
List<int> list = [];
while (queue.Count != 0) {
TreeNode node = queue.Dequeue(); // 队列出队
list.Add(node.val); // 保存节点值
list.Add(node.val!.Value); // 保存节点值
if (node.left != null)
queue.Enqueue(node.left); // 左子节点入队
if (node.right != null)
@ -449,7 +449,7 @@ comments: true
void PreOrder(TreeNode? root) {
if (root == null) return;
// 访问优先级:根节点 -> 左子树 -> 右子树
list.Add(root.val);
list.Add(root.val!.Value);
PreOrder(root.left);
PreOrder(root.right);
}
@ -459,7 +459,7 @@ comments: true
if (root == null) return;
// 访问优先级:左子树 -> 根节点 -> 右子树
InOrder(root.left);
list.Add(root.val);
list.Add(root.val!.Value);
InOrder(root.right);
}
@ -469,7 +469,7 @@ comments: true
// 访问优先级:左子树 -> 右子树 -> 根节点
PostOrder(root.left);
PostOrder(root.right);
list.Add(root.val);
list.Add(root.val!.Value);
}
```