From e2823e06c382a5c4d9baf629772dd659b8040ece Mon Sep 17 00:00:00 2001 From: hpstory <354195783@qq.com> Date: Fri, 24 Nov 2023 14:58:01 +0800 Subject: [PATCH 01/10] .net 8.0 migration --- codes/csharp/.editorconfig | 73 +++++++++++++++++++ .../chapter_array_and_linkedlist/array.cs | 2 +- .../linked_list.cs | 4 +- .../chapter_array_and_linkedlist/list.cs | 6 +- codes/csharp/chapter_backtracking/n_queens.cs | 8 +- .../chapter_backtracking/permutations_i.cs | 6 +- .../chapter_backtracking/permutations_ii.cs | 8 +- .../preorder_traversal_i_compact.cs | 7 +- .../preorder_traversal_ii_compact.cs | 10 +-- .../preorder_traversal_iii_compact.cs | 10 +-- .../preorder_traversal_iii_template.cs | 10 +-- .../chapter_backtracking/subset_sum_i.cs | 6 +- .../subset_sum_i_naive.cs | 6 +- .../chapter_backtracking/subset_sum_ii.cs | 6 +- .../recursion.cs | 6 +- .../space_complexity.cs | 8 +- .../time_complexity.cs | 14 ++-- .../binary_search_recur.cs | 6 +- .../chapter_divide_and_conquer/build_tree.cs | 14 ++-- .../chapter_divide_and_conquer/hanota.cs | 12 +-- .../climbing_stairs_backtrack.cs | 6 +- .../climbing_stairs_constraint_dp.cs | 2 +- .../climbing_stairs_dfs.cs | 4 +- .../climbing_stairs_dfs_mem.cs | 4 +- .../climbing_stairs_dp.cs | 4 +- .../coin_change.cs | 6 +- .../coin_change_ii.cs | 6 +- .../edit_distance.cs | 8 +- .../chapter_dynamic_programming/knapsack.cs | 12 +-- .../min_cost_climbing_stairs_dp.cs | 6 +- .../min_path_sum.cs | 20 ++--- .../unbounded_knapsack.cs | 8 +- .../chapter_graph/graph_adjacency_list.cs | 37 ++++++---- .../chapter_graph/graph_adjacency_matrix.cs | 18 +++-- codes/csharp/chapter_graph/graph_bfs.cs | 20 ++--- codes/csharp/chapter_graph/graph_dfs.cs | 20 ++--- .../chapter_greedy/coin_change_greedy.cs | 8 +- .../chapter_greedy/fractional_knapsack.cs | 17 ++--- codes/csharp/chapter_greedy/max_capacity.cs | 4 +- .../chapter_greedy/max_product_cutting.cs | 2 +- .../csharp/chapter_hashing/array_hash_map.cs | 20 ++--- codes/csharp/chapter_hashing/built_in_hash.cs | 2 +- .../chapter_hashing/hash_map_chaining.cs | 6 +- codes/csharp/chapter_heap/heap.cs | 4 +- codes/csharp/chapter_heap/my_heap.cs | 10 +-- codes/csharp/chapter_heap/top_k.cs | 2 +- .../csharp/chapter_searching/binary_search.cs | 2 +- .../chapter_searching/binary_search_edge.cs | 6 +- .../binary_search_insertion.cs | 6 +- .../chapter_searching/hashing_search.cs | 6 +- .../csharp/chapter_searching/linear_search.cs | 2 +- codes/csharp/chapter_searching/two_sum.cs | 12 +-- codes/csharp/chapter_sorting/bubble_sort.cs | 4 +- codes/csharp/chapter_sorting/bucket_sort.cs | 6 +- codes/csharp/chapter_sorting/counting_sort.cs | 4 +- codes/csharp/chapter_sorting/heap_sort.cs | 2 +- .../csharp/chapter_sorting/insertion_sort.cs | 2 +- codes/csharp/chapter_sorting/merge_sort.cs | 2 +- codes/csharp/chapter_sorting/quick_sort.cs | 6 +- codes/csharp/chapter_sorting/radix_sort.cs | 4 +- .../csharp/chapter_sorting/selection_sort.cs | 2 +- .../chapter_stack_and_queue/array_stack.cs | 4 +- .../linkedlist_deque.cs | 22 ++---- .../linkedlist_queue.cs | 8 +- .../linkedlist_stack.cs | 10 +-- .../csharp/chapter_tree/array_binary_tree.cs | 41 +++++------ codes/csharp/chapter_tree/avl_tree.cs | 30 ++++---- .../csharp/chapter_tree/binary_search_tree.cs | 8 +- codes/csharp/chapter_tree/binary_tree_bfs.cs | 10 +-- codes/csharp/chapter_tree/binary_tree_dfs.cs | 10 +-- codes/csharp/hello-algo.csproj | 13 ++-- codes/csharp/utils/ListNode.cs | 10 +-- codes/csharp/utils/PrintUtil.cs | 23 +++--- codes/csharp/utils/TreeNode.cs | 13 +--- codes/csharp/utils/Vertex.cs | 9 +-- 75 files changed, 403 insertions(+), 352 deletions(-) diff --git a/codes/csharp/.editorconfig b/codes/csharp/.editorconfig index 681df863a4..0ade0e81b5 100644 --- a/codes/csharp/.editorconfig +++ b/codes/csharp/.editorconfig @@ -4,3 +4,76 @@ csharp_new_line_before_open_brace = none csharp_new_line_before_else = false csharp_new_line_before_catch = false csharp_new_line_before_finally = false +csharp_indent_labels = one_less_than_current +csharp_using_directive_placement = outside_namespace:silent +csharp_prefer_simple_using_statement = true:suggestion +csharp_prefer_braces = true:silent +csharp_style_namespace_declarations = block_scoped:silent +csharp_style_prefer_method_group_conversion = true:silent +csharp_style_prefer_top_level_statements = true:silent +csharp_style_prefer_primary_constructors = true:suggestion +csharp_style_expression_bodied_methods = false:silent +csharp_style_expression_bodied_constructors = false:silent +csharp_style_expression_bodied_operators = false:silent +csharp_style_expression_bodied_properties = true:silent +csharp_style_expression_bodied_indexers = true:silent +csharp_style_expression_bodied_accessors = true:silent +csharp_style_expression_bodied_lambdas = true:silent + +# CS8981: The type name only contains lower-cased ascii characters. Such names may become reserved for the language. +dotnet_diagnostic.CS8981.severity = silent + +# IDE1006: Naming Styles +dotnet_diagnostic.IDE1006.severity = silent + +[*.{cs,vb}] +#### Naming styles #### + +# Naming rules + +dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion +dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface +dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i + +dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.types_should_be_pascal_case.symbols = types +dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members +dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case + +# Symbol specifications + +dotnet_naming_symbols.interface.applicable_kinds = interface +dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.interface.required_modifiers = + +dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum +dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.types.required_modifiers = + +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.non_field_members.required_modifiers = + +# Naming styles + +dotnet_naming_style.begins_with_i.required_prefix = I +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.begins_with_i.capitalization = pascal_case + +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case + +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case +dotnet_style_operator_placement_when_wrapping = beginning_of_line +tab_width = 4 +indent_size = 4 +end_of_line = crlf diff --git a/codes/csharp/chapter_array_and_linkedlist/array.cs b/codes/csharp/chapter_array_and_linkedlist/array.cs index dfab3a0511..fb0ff875b6 100644 --- a/codes/csharp/chapter_array_and_linkedlist/array.cs +++ b/codes/csharp/chapter_array_and_linkedlist/array.cs @@ -78,7 +78,7 @@ public static void Test() { // 初始化数组 int[] arr = new int[5]; Console.WriteLine("数组 arr = " + ToString(arr)); - int[] nums = { 1, 3, 2, 5, 4 }; + int[] nums = [1, 3, 2, 5, 4]; Console.WriteLine("数组 nums = " + ToString(nums)); // 随机访问 diff --git a/codes/csharp/chapter_array_and_linkedlist/linked_list.cs b/codes/csharp/chapter_array_and_linkedlist/linked_list.cs index 56d7e58eab..9cdfca68bd 100644 --- a/codes/csharp/chapter_array_and_linkedlist/linked_list.cs +++ b/codes/csharp/chapter_array_and_linkedlist/linked_list.cs @@ -23,7 +23,7 @@ public static void Remove(ListNode n0) { } /* 访问链表中索引为 index 的节点 */ - public static ListNode? Access(ListNode head, int index) { + public static ListNode? Access(ListNode? head, int index) { for (int i = 0; i < index; i++) { if (head == null) return null; @@ -33,7 +33,7 @@ public static void Remove(ListNode n0) { } /* 在链表中查找值为 target 的首个节点 */ - public static int Find(ListNode head, int target) { + public static int Find(ListNode? head, int target) { int index = 0; while (head != null) { if (head.val == target) diff --git a/codes/csharp/chapter_array_and_linkedlist/list.cs b/codes/csharp/chapter_array_and_linkedlist/list.cs index 72f3687bb3..1bd2a92c07 100644 --- a/codes/csharp/chapter_array_and_linkedlist/list.cs +++ b/codes/csharp/chapter_array_and_linkedlist/list.cs @@ -11,8 +11,8 @@ public class list { public void Test() { /* 初始化列表 */ - int[] numbers = new int[] { 1, 3, 2, 5, 4 }; - List nums = numbers.ToList(); + int[] numbers = [1, 3, 2, 5, 4]; + List nums = [.. numbers]; Console.WriteLine("列表 nums = " + string.Join(",", nums)); /* 访问元素 */ @@ -55,7 +55,7 @@ public void Test() { } /* 拼接两个列表 */ - List nums1 = new() { 6, 8, 7, 10, 9 }; + List nums1 = [6, 8, 7, 10, 9]; nums.AddRange(nums1); Console.WriteLine("将列表 nums1 拼接到 nums 之后,得到 nums = " + string.Join(",", nums)); diff --git a/codes/csharp/chapter_backtracking/n_queens.cs b/codes/csharp/chapter_backtracking/n_queens.cs index f31bcaefde..d19355de73 100644 --- a/codes/csharp/chapter_backtracking/n_queens.cs +++ b/codes/csharp/chapter_backtracking/n_queens.cs @@ -12,7 +12,7 @@ static void Backtrack(int row, int n, List> state, List> copyState = new(); + List> copyState = []; foreach (List sRow in state) { copyState.Add(new List(sRow)); } @@ -41,9 +41,9 @@ static void Backtrack(int row, int n, List> state, List>> NQueens(int n) { // 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位 - List> state = new(); + List> state = []; for (int i = 0; i < n; i++) { - List row = new(); + List row = []; for (int j = 0; j < n; j++) { row.Add("#"); } @@ -52,7 +52,7 @@ static List>> NQueens(int n) { bool[] cols = new bool[n]; // 记录列是否有皇后 bool[] diags1 = new bool[2 * n - 1]; // 记录主对角线是否有皇后 bool[] diags2 = new bool[2 * n - 1]; // 记录副对角线是否有皇后 - List>> res = new(); + List>> res = []; Backtrack(0, n, state, res, cols, diags1, diags2); diff --git a/codes/csharp/chapter_backtracking/permutations_i.cs b/codes/csharp/chapter_backtracking/permutations_i.cs index 40ffdc3f87..f294296eae 100644 --- a/codes/csharp/chapter_backtracking/permutations_i.cs +++ b/codes/csharp/chapter_backtracking/permutations_i.cs @@ -33,14 +33,14 @@ static void Backtrack(List state, int[] choices, bool[] selected, List> PermutationsI(int[] nums) { - List> res = new(); - Backtrack(new List(), nums, new bool[nums.Length], res); + List> res = []; + Backtrack([], nums, new bool[nums.Length], res); return res; } [Test] public void Test() { - int[] nums = { 1, 2, 3 }; + int[] nums = [1, 2, 3]; List> res = PermutationsI(nums); diff --git a/codes/csharp/chapter_backtracking/permutations_ii.cs b/codes/csharp/chapter_backtracking/permutations_ii.cs index cbbbb96cdd..08233d01c1 100644 --- a/codes/csharp/chapter_backtracking/permutations_ii.cs +++ b/codes/csharp/chapter_backtracking/permutations_ii.cs @@ -15,7 +15,7 @@ static void Backtrack(List state, int[] choices, bool[] selected, List duplicated = new HashSet(); + HashSet duplicated = []; for (int i = 0; i < choices.Length; i++) { int choice = choices[i]; // 剪枝:不允许重复选择元素 且 不允许重复选择相等元素 @@ -35,14 +35,14 @@ static void Backtrack(List state, int[] choices, bool[] selected, List> PermutationsII(int[] nums) { - List> res = new(); - Backtrack(new List(), nums, new bool[nums.Length], res); + List> res = []; + Backtrack([], nums, new bool[nums.Length], res); return res; } [Test] public void Test() { - int[] nums = { 1, 2, 2 }; + int[] nums = [1, 2, 2]; List> res = PermutationsII(nums); diff --git a/codes/csharp/chapter_backtracking/preorder_traversal_i_compact.cs b/codes/csharp/chapter_backtracking/preorder_traversal_i_compact.cs index 4140dc2def..bbc0171df4 100644 --- a/codes/csharp/chapter_backtracking/preorder_traversal_i_compact.cs +++ b/codes/csharp/chapter_backtracking/preorder_traversal_i_compact.cs @@ -7,10 +7,10 @@ namespace hello_algo.chapter_backtracking; public class preorder_traversal_i_compact { - static List res; + static readonly List res = []; /* 前序遍历:例题一 */ - static void PreOrder(TreeNode root) { + static void PreOrder(TreeNode? root) { if (root == null) { return; } @@ -24,12 +24,11 @@ static void PreOrder(TreeNode root) { [Test] public void Test() { - TreeNode root = TreeNode.ListToTree(new List { 1, 7, 3, 4, 5, 6, 7 }); + TreeNode? root = TreeNode.ListToTree([1, 7, 3, 4, 5, 6, 7]); Console.WriteLine("\n初始化二叉树"); PrintUtil.PrintTree(root); // 前序遍历 - res = new List(); PreOrder(root); Console.WriteLine("\n输出所有值为 7 的节点"); diff --git a/codes/csharp/chapter_backtracking/preorder_traversal_ii_compact.cs b/codes/csharp/chapter_backtracking/preorder_traversal_ii_compact.cs index bd525af5e4..7089465870 100644 --- a/codes/csharp/chapter_backtracking/preorder_traversal_ii_compact.cs +++ b/codes/csharp/chapter_backtracking/preorder_traversal_ii_compact.cs @@ -7,11 +7,11 @@ namespace hello_algo.chapter_backtracking; public class preorder_traversal_ii_compact { - static List path; - static List> res; + static readonly List path = []; + static readonly List> res = []; /* 前序遍历:例题二 */ - static void PreOrder(TreeNode root) { + static void PreOrder(TreeNode? root) { if (root == null) { return; } @@ -29,13 +29,11 @@ static void PreOrder(TreeNode root) { [Test] public void Test() { - TreeNode root = TreeNode.ListToTree(new List { 1, 7, 3, 4, 5, 6, 7 }); + TreeNode? root = TreeNode.ListToTree([1, 7, 3, 4, 5, 6, 7]); Console.WriteLine("\n初始化二叉树"); PrintUtil.PrintTree(root); // 前序遍历 - path = new List(); - res = new List>(); PreOrder(root); Console.WriteLine("\n输出所有根节点到节点 7 的路径"); diff --git a/codes/csharp/chapter_backtracking/preorder_traversal_iii_compact.cs b/codes/csharp/chapter_backtracking/preorder_traversal_iii_compact.cs index ac0b57af62..9cf32bd231 100644 --- a/codes/csharp/chapter_backtracking/preorder_traversal_iii_compact.cs +++ b/codes/csharp/chapter_backtracking/preorder_traversal_iii_compact.cs @@ -7,11 +7,11 @@ namespace hello_algo.chapter_backtracking; public class preorder_traversal_iii_compact { - static List path; - static List> res; + static readonly List path = []; + static readonly List> res = []; /* 前序遍历:例题三 */ - static void PreOrder(TreeNode root) { + static void PreOrder(TreeNode? root) { // 剪枝 if (root == null || root.val == 3) { return; @@ -30,13 +30,11 @@ static void PreOrder(TreeNode root) { [Test] public void Test() { - TreeNode root = TreeNode.ListToTree(new List { 1, 7, 3, 4, 5, 6, 7 }); + TreeNode? root = TreeNode.ListToTree([1, 7, 3, 4, 5, 6, 7]); Console.WriteLine("\n初始化二叉树"); PrintUtil.PrintTree(root); // 前序遍历 - path = new List(); - res = new List>(); PreOrder(root); Console.WriteLine("\n输出所有根节点到节点 7 的路径,路径中不包含值为 3 的节点"); diff --git a/codes/csharp/chapter_backtracking/preorder_traversal_iii_template.cs b/codes/csharp/chapter_backtracking/preorder_traversal_iii_template.cs index d9da5b0e92..6fda6d8f88 100644 --- a/codes/csharp/chapter_backtracking/preorder_traversal_iii_template.cs +++ b/codes/csharp/chapter_backtracking/preorder_traversal_iii_template.cs @@ -46,7 +46,7 @@ static void Backtrack(List state, List choices, List { choice.left, choice.right }, res); + Backtrack(state, [choice.left!, choice.right!], res); // 回退:撤销选择,恢复到之前的状态 UndoChoice(state, choice); } @@ -55,14 +55,14 @@ static void Backtrack(List state, List choices, List { 1, 7, 3, 4, 5, 6, 7 }); + TreeNode? root = TreeNode.ListToTree([1, 7, 3, 4, 5, 6, 7]); Console.WriteLine("\n初始化二叉树"); PrintUtil.PrintTree(root); // 回溯算法 - List> res = new(); - List choices = new() { root }; - Backtrack(new List(), choices, res); + List> res = []; + List choices = [root!]; + Backtrack([], choices, res); Console.WriteLine("\n输出所有根节点到节点 7 的路径,要求路径中不包含值为 3 的节点"); foreach (List path in res) { diff --git a/codes/csharp/chapter_backtracking/subset_sum_i.cs b/codes/csharp/chapter_backtracking/subset_sum_i.cs index 3988b6bde1..0cf9d025b2 100644 --- a/codes/csharp/chapter_backtracking/subset_sum_i.cs +++ b/codes/csharp/chapter_backtracking/subset_sum_i.cs @@ -33,17 +33,17 @@ public static void Backtrack(List state, int target, int[] choices, int sta /* 求解子集和 I */ public static List> SubsetSumI(int[] nums, int target) { - List state = new(); // 状态(子集) + List state = []; // 状态(子集) Array.Sort(nums); // 对 nums 进行排序 int start = 0; // 遍历起始点 - List> res = new(); // 结果列表(子集列表) + List> res = []; // 结果列表(子集列表) Backtrack(state, target, nums, start, res); return res; } [Test] public void Test() { - int[] nums = { 3, 4, 5 }; + int[] nums = [3, 4, 5]; int target = 9; List> res = SubsetSumI(nums, target); Console.WriteLine("输入数组 nums = " + string.Join(", ", nums) + ", target = " + target); diff --git a/codes/csharp/chapter_backtracking/subset_sum_i_naive.cs b/codes/csharp/chapter_backtracking/subset_sum_i_naive.cs index a4d6718882..aebbdf3134 100644 --- a/codes/csharp/chapter_backtracking/subset_sum_i_naive.cs +++ b/codes/csharp/chapter_backtracking/subset_sum_i_naive.cs @@ -31,16 +31,16 @@ public static void Backtrack(List state, int target, int total, int[] choic /* 求解子集和 I(包含重复子集) */ public static List> SubsetSumINaive(int[] nums, int target) { - List state = new(); // 状态(子集) + List state = []; // 状态(子集) int total = 0; // 子集和 - List> res = new(); // 结果列表(子集列表) + List> res = []; // 结果列表(子集列表) Backtrack(state, target, total, nums, res); return res; } [Test] public void Test() { - int[] nums = { 3, 4, 5 }; + int[] nums = [3, 4, 5]; int target = 9; List> res = SubsetSumINaive(nums, target); Console.WriteLine("输入数组 nums = " + string.Join(", ", nums) + ", target = " + target); diff --git a/codes/csharp/chapter_backtracking/subset_sum_ii.cs b/codes/csharp/chapter_backtracking/subset_sum_ii.cs index 10225233b3..1e22589dcf 100644 --- a/codes/csharp/chapter_backtracking/subset_sum_ii.cs +++ b/codes/csharp/chapter_backtracking/subset_sum_ii.cs @@ -38,17 +38,17 @@ public static void Backtrack(List state, int target, int[] choices, int sta /* 求解子集和 II */ public static List> SubsetSumII(int[] nums, int target) { - List state = new(); // 状态(子集) + List state = []; // 状态(子集) Array.Sort(nums); // 对 nums 进行排序 int start = 0; // 遍历起始点 - List> res = new(); // 结果列表(子集列表) + List> res = []; // 结果列表(子集列表) Backtrack(state, target, nums, start, res); return res; } [Test] public void Test() { - int[] nums = { 4, 4, 5 }; + int[] nums = [4, 4, 5]; int target = 9; List> res = SubsetSumII(nums, target); Console.WriteLine("输入数组 nums = " + string.Join(", ", nums) + ", target = " + target); diff --git a/codes/csharp/chapter_computational_complexity/recursion.cs b/codes/csharp/chapter_computational_complexity/recursion.cs index 0d010fedcd..475641de83 100644 --- a/codes/csharp/chapter_computational_complexity/recursion.cs +++ b/codes/csharp/chapter_computational_complexity/recursion.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_computational_complexity; public class recursion { /* 递归 */ - public int Recur(int n) { + public static int Recur(int n) { // 终止条件 if (n == 1) return 1; @@ -38,7 +38,7 @@ public static int ForLoopRecur(int n) { } /* 尾递归 */ - public int TailRecur(int n, int res) { + public static int TailRecur(int n, int res) { // 终止条件 if (n == 0) return res; @@ -47,7 +47,7 @@ public int TailRecur(int n, int res) { } /* 斐波那契数列:递归 */ - public int Fib(int n) { + public static int Fib(int n) { // 终止条件 f(1) = 0, f(2) = 1 if (n == 1 || n == 2) return n - 1; diff --git a/codes/csharp/chapter_computational_complexity/space_complexity.cs b/codes/csharp/chapter_computational_complexity/space_complexity.cs index 00bb6e6c5c..c763f58f9f 100644 --- a/codes/csharp/chapter_computational_complexity/space_complexity.cs +++ b/codes/csharp/chapter_computational_complexity/space_complexity.cs @@ -35,12 +35,12 @@ static void Linear(int n) { // 长度为 n 的数组占用 O(n) 空间 int[] nums = new int[n]; // 长度为 n 的列表占用 O(n) 空间 - List nodes = new(); + List nodes = []; for (int i = 0; i < n; i++) { nodes.Add(new ListNode(i)); } // 长度为 n 的哈希表占用 O(n) 空间 - Dictionary map = new(); + Dictionary map = []; for (int i = 0; i < n; i++) { map.Add(i, i.ToString()); } @@ -58,9 +58,9 @@ static void Quadratic(int n) { // 矩阵占用 O(n^2) 空间 int[,] numMatrix = new int[n, n]; // 二维列表占用 O(n^2) 空间 - List> numList = new(); + List> numList = []; for (int i = 0; i < n; i++) { - List tmp = new(); + List tmp = []; for (int j = 0; j < n; j++) { tmp.Add(0); } diff --git a/codes/csharp/chapter_computational_complexity/time_complexity.cs b/codes/csharp/chapter_computational_complexity/time_complexity.cs index 42e51ce02a..e206f0c79a 100644 --- a/codes/csharp/chapter_computational_complexity/time_complexity.cs +++ b/codes/csharp/chapter_computational_complexity/time_complexity.cs @@ -7,9 +7,9 @@ namespace hello_algo.chapter_computational_complexity; public class time_complexity { - void Algorithm(int n) { + public static void Algorithm(int n) { int a = 1; // +0(技巧 1) - a = a + n; // +0(技巧 1) + a += n; // +0(技巧 1) // +n(技巧 2) for (int i = 0; i < 5 * n + 1; i++) { Console.WriteLine(0); @@ -23,17 +23,19 @@ void Algorithm(int n) { } // 算法 A 时间复杂度:常数阶 - void AlgorithmA(int n) { + public static void AlgorithmA(int n) { Console.WriteLine(0); } + // 算法 B 时间复杂度:线性阶 - void AlgorithmB(int n) { + public static void AlgorithmB(int n) { for (int i = 0; i < n; i++) { Console.WriteLine(0); } } + // 算法 C 时间复杂度:常数阶 - void AlgorithmC(int n) { + public static void AlgorithmC(int n) { for (int i = 0; i < 1000000; i++) { Console.WriteLine(0); } @@ -119,7 +121,7 @@ static int ExpRecur(int n) { static int Logarithmic(float n) { int count = 0; while (n > 1) { - n = n / 2; + n /= 2; count++; } return count; diff --git a/codes/csharp/chapter_divide_and_conquer/binary_search_recur.cs b/codes/csharp/chapter_divide_and_conquer/binary_search_recur.cs index 69d9dc7055..2a15c1de49 100644 --- a/codes/csharp/chapter_divide_and_conquer/binary_search_recur.cs +++ b/codes/csharp/chapter_divide_and_conquer/binary_search_recur.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_divide_and_conquer; public class binary_search_recur { /* 二分查找:问题 f(i, j) */ - public int DFS(int[] nums, int target, int i, int j) { + public static int DFS(int[] nums, int target, int i, int j) { // 若区间为空,代表无目标元素,则返回 -1 if (i > j) { return -1; @@ -28,7 +28,7 @@ public int DFS(int[] nums, int target, int i, int j) { } /* 二分查找 */ - public int BinarySearch(int[] nums, int target) { + public static int BinarySearch(int[] nums, int target) { int n = nums.Length; // 求解问题 f(0, n-1) return DFS(nums, target, 0, n - 1); @@ -37,7 +37,7 @@ public int BinarySearch(int[] nums, int target) { [Test] public void Test() { int target = 6; - int[] nums = { 1, 3, 6, 8, 12, 15, 23, 26, 31, 35 }; + int[] nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35]; // 二分查找(双闭区间) int index = BinarySearch(nums, target); diff --git a/codes/csharp/chapter_divide_and_conquer/build_tree.cs b/codes/csharp/chapter_divide_and_conquer/build_tree.cs index fe0bc09c7c..89d9e5a3fa 100644 --- a/codes/csharp/chapter_divide_and_conquer/build_tree.cs +++ b/codes/csharp/chapter_divide_and_conquer/build_tree.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_divide_and_conquer; public class build_tree { /* 构建二叉树:分治 */ - public TreeNode DFS(int[] preorder, Dictionary inorderMap, int i, int l, int r) { + public static TreeNode? DFS(int[] preorder, Dictionary inorderMap, int i, int l, int r) { // 子树区间为空时终止 if (r - l < 0) return null; @@ -25,24 +25,24 @@ public TreeNode DFS(int[] preorder, Dictionary inorderMap, int i, int } /* 构建二叉树 */ - public TreeNode BuildTree(int[] preorder, int[] inorder) { + public static TreeNode? BuildTree(int[] preorder, int[] inorder) { // 初始化哈希表,存储 inorder 元素到索引的映射 - Dictionary inorderMap = new(); + Dictionary 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; } [Test] public void Test() { - int[] preorder = { 3, 9, 2, 1, 7 }; - int[] inorder = { 9, 3, 1, 2, 7 }; + int[] preorder = [3, 9, 2, 1, 7]; + int[] inorder = [9, 3, 1, 2, 7]; Console.WriteLine("前序遍历 = " + string.Join(", ", preorder)); Console.WriteLine("中序遍历 = " + string.Join(", ", inorder)); - TreeNode root = BuildTree(preorder, inorder); + TreeNode? root = BuildTree(preorder, inorder); Console.WriteLine("构建的二叉树为:"); PrintUtil.PrintTree(root); } diff --git a/codes/csharp/chapter_divide_and_conquer/hanota.cs b/codes/csharp/chapter_divide_and_conquer/hanota.cs index 558ecba82f..d1007b9c3c 100644 --- a/codes/csharp/chapter_divide_and_conquer/hanota.cs +++ b/codes/csharp/chapter_divide_and_conquer/hanota.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_divide_and_conquer; public class hanota { /* 移动一个圆盘 */ - public void Move(List src, List tar) { + public static void Move(List src, List tar) { // 从 src 顶部拿出一个圆盘 int pan = src[^1]; src.RemoveAt(src.Count - 1); @@ -17,7 +17,7 @@ public void Move(List src, List tar) { } /* 求解汉诺塔:问题 f(i) */ - public void DFS(int i, List src, List buf, List tar) { + public static void DFS(int i, List src, List buf, List tar) { // 若 src 只剩下一个圆盘,则直接将其移到 tar if (i == 1) { Move(src, tar); @@ -32,7 +32,7 @@ public void DFS(int i, List src, List buf, List tar) { } /* 求解汉诺塔 */ - public void SolveHanota(List A, List B, List C) { + public static void SolveHanota(List A, List B, List C) { int n = A.Count; // 将 A 顶部 n 个圆盘借助 B 移到 C DFS(n, A, B, C); @@ -41,9 +41,9 @@ public void SolveHanota(List A, List B, List C) { [Test] public void Test() { // 列表尾部是柱子顶部 - List A = new() { 5, 4, 3, 2, 1 }; - List B = new(); - List C = new(); + List A = [5, 4, 3, 2, 1]; + List B = []; + List C = []; Console.WriteLine("初始状态下:"); Console.WriteLine("A = " + string.Join(", ", A)); Console.WriteLine("B = " + string.Join(", ", B)); diff --git a/codes/csharp/chapter_dynamic_programming/climbing_stairs_backtrack.cs b/codes/csharp/chapter_dynamic_programming/climbing_stairs_backtrack.cs index 3cbae96881..93a0fed868 100644 --- a/codes/csharp/chapter_dynamic_programming/climbing_stairs_backtrack.cs +++ b/codes/csharp/chapter_dynamic_programming/climbing_stairs_backtrack.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_dynamic_programming; public class climbing_stairs_backtrack { /* 回溯 */ - public void Backtrack(List choices, int state, int n, List res) { + public static void Backtrack(List choices, int state, int n, List res) { // 当爬到第 n 阶时,方案数量加 1 if (state == n) res[0]++; @@ -25,9 +25,9 @@ public void Backtrack(List choices, int state, int n, List res) { /* 爬楼梯:回溯 */ public int ClimbingStairsBacktrack(int n) { - List choices = new() { 1, 2 }; // 可选择向上爬 1 或 2 阶 + List choices = [1, 2]; // 可选择向上爬 1 或 2 阶 int state = 0; // 从第 0 阶开始爬 - List res = new() { 0 }; // 使用 res[0] 记录方案数量 + List res = [0]; // 使用 res[0] 记录方案数量 Backtrack(choices, state, n, res); return res[0]; } diff --git a/codes/csharp/chapter_dynamic_programming/climbing_stairs_constraint_dp.cs b/codes/csharp/chapter_dynamic_programming/climbing_stairs_constraint_dp.cs index cf2b706615..16be10ec2f 100644 --- a/codes/csharp/chapter_dynamic_programming/climbing_stairs_constraint_dp.cs +++ b/codes/csharp/chapter_dynamic_programming/climbing_stairs_constraint_dp.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_dynamic_programming; public class climbing_stairs_constraint_dp { /* 带约束爬楼梯:动态规划 */ - public int ClimbingStairsConstraintDP(int n) { + public static int ClimbingStairsConstraintDP(int n) { if (n == 1 || n == 2) { return 1; } diff --git a/codes/csharp/chapter_dynamic_programming/climbing_stairs_dfs.cs b/codes/csharp/chapter_dynamic_programming/climbing_stairs_dfs.cs index 6496001619..8839e00f94 100644 --- a/codes/csharp/chapter_dynamic_programming/climbing_stairs_dfs.cs +++ b/codes/csharp/chapter_dynamic_programming/climbing_stairs_dfs.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_dynamic_programming; public class climbing_stairs_dfs { /* 搜索 */ - public int DFS(int i) { + public static int DFS(int i) { // 已知 dp[1] 和 dp[2] ,返回之 if (i == 1 || i == 2) return i; @@ -18,7 +18,7 @@ public int DFS(int i) { } /* 爬楼梯:搜索 */ - public int ClimbingStairsDFS(int n) { + public static int ClimbingStairsDFS(int n) { return DFS(n); } diff --git a/codes/csharp/chapter_dynamic_programming/climbing_stairs_dfs_mem.cs b/codes/csharp/chapter_dynamic_programming/climbing_stairs_dfs_mem.cs index 220aaa6ea6..596db264a7 100644 --- a/codes/csharp/chapter_dynamic_programming/climbing_stairs_dfs_mem.cs +++ b/codes/csharp/chapter_dynamic_programming/climbing_stairs_dfs_mem.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_dynamic_programming; public class climbing_stairs_dfs_mem { /* 记忆化搜索 */ - public int DFS(int i, int[] mem) { + public static int DFS(int i, int[] mem) { // 已知 dp[1] 和 dp[2] ,返回之 if (i == 1 || i == 2) return i; @@ -23,7 +23,7 @@ public int DFS(int i, int[] mem) { } /* 爬楼梯:记忆化搜索 */ - public int ClimbingStairsDFSMem(int n) { + public static int ClimbingStairsDFSMem(int n) { // mem[i] 记录爬到第 i 阶的方案总数,-1 代表无记录 int[] mem = new int[n + 1]; Array.Fill(mem, -1); diff --git a/codes/csharp/chapter_dynamic_programming/climbing_stairs_dp.cs b/codes/csharp/chapter_dynamic_programming/climbing_stairs_dp.cs index 2786bfb3d1..5794f83acb 100644 --- a/codes/csharp/chapter_dynamic_programming/climbing_stairs_dp.cs +++ b/codes/csharp/chapter_dynamic_programming/climbing_stairs_dp.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_dynamic_programming; public class climbing_stairs_dp { /* 爬楼梯:动态规划 */ - public int ClimbingStairsDP(int n) { + public static int ClimbingStairsDP(int n) { if (n == 1 || n == 2) return n; // 初始化 dp 表,用于存储子问题的解 @@ -24,7 +24,7 @@ public int ClimbingStairsDP(int n) { } /* 爬楼梯:空间优化后的动态规划 */ - public int ClimbingStairsDPComp(int n) { + public static int ClimbingStairsDPComp(int n) { if (n == 1 || n == 2) return n; int a = 1, b = 2; diff --git a/codes/csharp/chapter_dynamic_programming/coin_change.cs b/codes/csharp/chapter_dynamic_programming/coin_change.cs index b8e06b6df8..0187bbd8fd 100644 --- a/codes/csharp/chapter_dynamic_programming/coin_change.cs +++ b/codes/csharp/chapter_dynamic_programming/coin_change.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_dynamic_programming; public class coin_change { /* 零钱兑换:动态规划 */ - public int CoinChangeDP(int[] coins, int amt) { + public static int CoinChangeDP(int[] coins, int amt) { int n = coins.Length; int MAX = amt + 1; // 初始化 dp 表 @@ -33,7 +33,7 @@ public int CoinChangeDP(int[] coins, int amt) { } /* 零钱兑换:空间优化后的动态规划 */ - public int CoinChangeDPComp(int[] coins, int amt) { + public static int CoinChangeDPComp(int[] coins, int amt) { int n = coins.Length; int MAX = amt + 1; // 初始化 dp 表 @@ -57,7 +57,7 @@ public int CoinChangeDPComp(int[] coins, int amt) { [Test] public void Test() { - int[] coins = { 1, 2, 5 }; + int[] coins = [1, 2, 5]; int amt = 4; // 动态规划 diff --git a/codes/csharp/chapter_dynamic_programming/coin_change_ii.cs b/codes/csharp/chapter_dynamic_programming/coin_change_ii.cs index 381f5d7c83..3d8946ca6e 100644 --- a/codes/csharp/chapter_dynamic_programming/coin_change_ii.cs +++ b/codes/csharp/chapter_dynamic_programming/coin_change_ii.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_dynamic_programming; public class coin_change_ii { /* 零钱兑换 II:动态规划 */ - public int CoinChangeIIDP(int[] coins, int amt) { + public static int CoinChangeIIDP(int[] coins, int amt) { int n = coins.Length; // 初始化 dp 表 int[,] dp = new int[n + 1, amt + 1]; @@ -32,7 +32,7 @@ public int CoinChangeIIDP(int[] coins, int amt) { } /* 零钱兑换 II:空间优化后的动态规划 */ - public int CoinChangeIIDPComp(int[] coins, int amt) { + public static int CoinChangeIIDPComp(int[] coins, int amt) { int n = coins.Length; // 初始化 dp 表 int[] dp = new int[amt + 1]; @@ -54,7 +54,7 @@ public int CoinChangeIIDPComp(int[] coins, int amt) { [Test] public void Test() { - int[] coins = { 1, 2, 5 }; + int[] coins = [1, 2, 5]; int amt = 5; // 动态规划 diff --git a/codes/csharp/chapter_dynamic_programming/edit_distance.cs b/codes/csharp/chapter_dynamic_programming/edit_distance.cs index 37189fe67a..58b076710a 100644 --- a/codes/csharp/chapter_dynamic_programming/edit_distance.cs +++ b/codes/csharp/chapter_dynamic_programming/edit_distance.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_dynamic_programming; public class edit_distance { /* 编辑距离:暴力搜索 */ - public int EditDistanceDFS(string s, string t, int i, int j) { + public static int EditDistanceDFS(string s, string t, int i, int j) { // 若 s 和 t 都为空,则返回 0 if (i == 0 && j == 0) return 0; @@ -30,7 +30,7 @@ public int EditDistanceDFS(string s, string t, int i, int j) { } /* 编辑距离:记忆化搜索 */ - public int EditDistanceDFSMem(string s, string t, int[][] mem, int i, int j) { + public static int EditDistanceDFSMem(string s, string t, int[][] mem, int i, int j) { // 若 s 和 t 都为空,则返回 0 if (i == 0 && j == 0) return 0; @@ -56,7 +56,7 @@ public int EditDistanceDFSMem(string s, string t, int[][] mem, int i, int j) { } /* 编辑距离:动态规划 */ - public int EditDistanceDP(string s, string t) { + public static int EditDistanceDP(string s, string t) { int n = s.Length, m = t.Length; int[,] dp = new int[n + 1, m + 1]; // 状态转移:首行首列 @@ -82,7 +82,7 @@ public int EditDistanceDP(string s, string t) { } /* 编辑距离:空间优化后的动态规划 */ - public int EditDistanceDPComp(string s, string t) { + public static int EditDistanceDPComp(string s, string t) { int n = s.Length, m = t.Length; int[] dp = new int[m + 1]; // 状态转移:首行 diff --git a/codes/csharp/chapter_dynamic_programming/knapsack.cs b/codes/csharp/chapter_dynamic_programming/knapsack.cs index eda8001ea1..545ee8a161 100644 --- a/codes/csharp/chapter_dynamic_programming/knapsack.cs +++ b/codes/csharp/chapter_dynamic_programming/knapsack.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_dynamic_programming; public class knapsack { /* 0-1 背包:暴力搜索 */ - public int KnapsackDFS(int[] weight, int[] val, int i, int c) { + public static int KnapsackDFS(int[] weight, int[] val, int i, int c) { // 若已选完所有物品或背包无容量,则返回价值 0 if (i == 0 || c == 0) { return 0; @@ -25,7 +25,7 @@ public int KnapsackDFS(int[] weight, int[] val, int i, int c) { } /* 0-1 背包:记忆化搜索 */ - public int KnapsackDFSMem(int[] weight, int[] val, int[][] mem, int i, int c) { + public static int KnapsackDFSMem(int[] weight, int[] val, int[][] mem, int i, int c) { // 若已选完所有物品或背包无容量,则返回价值 0 if (i == 0 || c == 0) { return 0; @@ -47,7 +47,7 @@ public int KnapsackDFSMem(int[] weight, int[] val, int[][] mem, int i, int c) { } /* 0-1 背包:动态规划 */ - public int KnapsackDP(int[] weight, int[] val, int cap) { + public static int KnapsackDP(int[] weight, int[] val, int cap) { int n = weight.Length; // 初始化 dp 表 int[,] dp = new int[n + 1, cap + 1]; @@ -67,7 +67,7 @@ public int KnapsackDP(int[] weight, int[] val, int cap) { } /* 0-1 背包:空间优化后的动态规划 */ - public int KnapsackDPComp(int[] weight, int[] val, int cap) { + public static int KnapsackDPComp(int[] weight, int[] val, int cap) { int n = weight.Length; // 初始化 dp 表 int[] dp = new int[cap + 1]; @@ -89,8 +89,8 @@ public int KnapsackDPComp(int[] weight, int[] val, int cap) { [Test] public void Test() { - int[] weight = { 10, 20, 30, 40, 50 }; - int[] val = { 50, 120, 150, 210, 240 }; + int[] weight = [10, 20, 30, 40, 50]; + int[] val = [50, 120, 150, 210, 240]; int cap = 50; int n = weight.Length; diff --git a/codes/csharp/chapter_dynamic_programming/min_cost_climbing_stairs_dp.cs b/codes/csharp/chapter_dynamic_programming/min_cost_climbing_stairs_dp.cs index 1872e1cf3b..5992540c89 100644 --- a/codes/csharp/chapter_dynamic_programming/min_cost_climbing_stairs_dp.cs +++ b/codes/csharp/chapter_dynamic_programming/min_cost_climbing_stairs_dp.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_dynamic_programming; public class min_cost_climbing_stairs_dp { /* 爬楼梯最小代价:动态规划 */ - public int MinCostClimbingStairsDP(int[] cost) { + public static int MinCostClimbingStairsDP(int[] cost) { int n = cost.Length - 1; if (n == 1 || n == 2) return cost[n]; @@ -25,7 +25,7 @@ public int MinCostClimbingStairsDP(int[] cost) { } /* 爬楼梯最小代价:空间优化后的动态规划 */ - public int MinCostClimbingStairsDPComp(int[] cost) { + public static int MinCostClimbingStairsDPComp(int[] cost) { int n = cost.Length - 1; if (n == 1 || n == 2) return cost[n]; @@ -40,7 +40,7 @@ public int MinCostClimbingStairsDPComp(int[] cost) { [Test] public void Test() { - int[] cost = { 0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1 }; + int[] cost = [0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1]; Console.WriteLine("输入楼梯的代价列表为"); PrintUtil.PrintList(cost); diff --git a/codes/csharp/chapter_dynamic_programming/min_path_sum.cs b/codes/csharp/chapter_dynamic_programming/min_path_sum.cs index a99c5592a6..72f2f10bc7 100644 --- a/codes/csharp/chapter_dynamic_programming/min_path_sum.cs +++ b/codes/csharp/chapter_dynamic_programming/min_path_sum.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_dynamic_programming; public class min_path_sum { /* 最小路径和:暴力搜索 */ - public int MinPathSumDFS(int[][] grid, int i, int j) { + public static int MinPathSumDFS(int[][] grid, int i, int j) { // 若为左上角单元格,则终止搜索 if (i == 0 && j == 0) { return grid[0][0]; @@ -25,7 +25,7 @@ public int MinPathSumDFS(int[][] grid, int i, int j) { } /* 最小路径和:记忆化搜索 */ - public int MinPathSumDFSMem(int[][] grid, int[][] mem, int i, int j) { + public static int MinPathSumDFSMem(int[][] grid, int[][] mem, int i, int j) { // 若为左上角单元格,则终止搜索 if (i == 0 && j == 0) { return grid[0][0]; @@ -47,7 +47,7 @@ public int MinPathSumDFSMem(int[][] grid, int[][] mem, int i, int j) { } /* 最小路径和:动态规划 */ - public int MinPathSumDP(int[][] grid) { + public static int MinPathSumDP(int[][] grid) { int n = grid.Length, m = grid[0].Length; // 初始化 dp 表 int[,] dp = new int[n, m]; @@ -70,7 +70,7 @@ public int MinPathSumDP(int[][] grid) { } /* 最小路径和:空间优化后的动态规划 */ - public int MinPathSumDPComp(int[][] grid) { + public static int MinPathSumDPComp(int[][] grid) { int n = grid.Length, m = grid[0].Length; // 初始化 dp 表 int[] dp = new int[m]; @@ -94,12 +94,12 @@ public int MinPathSumDPComp(int[][] grid) { [Test] public void Test() { int[][] grid = - { - new int[4] { 1, 3, 1, 5 }, - new int[4] { 2, 2, 4, 2 }, - new int[4] { 5, 3, 2, 1 }, - new int[4] { 4, 3, 5, 2 } - }; + [ + [1, 3, 1, 5], + [2, 2, 4, 2], + [5, 3, 2, 1], + [4, 3, 5, 2] + ]; int n = grid.Length, m = grid[0].Length; diff --git a/codes/csharp/chapter_dynamic_programming/unbounded_knapsack.cs b/codes/csharp/chapter_dynamic_programming/unbounded_knapsack.cs index aefbfc892a..154fcf3ea8 100644 --- a/codes/csharp/chapter_dynamic_programming/unbounded_knapsack.cs +++ b/codes/csharp/chapter_dynamic_programming/unbounded_knapsack.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_dynamic_programming; public class unbounded_knapsack { /* 完全背包:动态规划 */ - public int UnboundedKnapsackDP(int[] wgt, int[] val, int cap) { + public static int UnboundedKnapsackDP(int[] wgt, int[] val, int cap) { int n = wgt.Length; // 初始化 dp 表 int[,] dp = new int[n + 1, cap + 1]; @@ -28,7 +28,7 @@ public int UnboundedKnapsackDP(int[] wgt, int[] val, int cap) { } /* 完全背包:空间优化后的动态规划 */ - public int UnboundedKnapsackDPComp(int[] wgt, int[] val, int cap) { + public static int UnboundedKnapsackDPComp(int[] wgt, int[] val, int cap) { int n = wgt.Length; // 初始化 dp 表 int[] dp = new int[cap + 1]; @@ -49,8 +49,8 @@ public int UnboundedKnapsackDPComp(int[] wgt, int[] val, int cap) { [Test] public void Test() { - int[] wgt = { 1, 2, 3 }; - int[] val = { 5, 11, 15 }; + int[] wgt = [1, 2, 3]; + int[] val = [5, 11, 15]; int cap = 4; // 动态规划 diff --git a/codes/csharp/chapter_graph/graph_adjacency_list.cs b/codes/csharp/chapter_graph/graph_adjacency_list.cs index 8271f60538..f62638e355 100644 --- a/codes/csharp/chapter_graph/graph_adjacency_list.cs +++ b/codes/csharp/chapter_graph/graph_adjacency_list.cs @@ -13,7 +13,7 @@ public class GraphAdjList { /* 构造函数 */ public GraphAdjList(Vertex[][] edges) { - this.adjList = new Dictionary>(); + this.adjList = []; // 添加所有顶点和边 foreach (Vertex[] edge in edges) { AddVertex(edge[0]); @@ -29,20 +29,23 @@ public int Size() { /* 添加边 */ public void AddEdge(Vertex vet1, Vertex vet2) { - if (!adjList.ContainsKey(vet1) || !adjList.ContainsKey(vet2) || vet1 == vet2) + if (!adjList.TryGetValue(vet1, out List? vectors1) + || !adjList.TryGetValue(vet2, out List? vectors2) + || vet1 == vet2) throw new InvalidOperationException(); - // 添加边 vet1 - vet2 - adjList[vet1].Add(vet2); - adjList[vet2].Add(vet1); + vectors1.Add(vet2); + vectors2.Add(vet1); } /* 删除边 */ public void RemoveEdge(Vertex vet1, Vertex vet2) { - if (!adjList.ContainsKey(vet1) || !adjList.ContainsKey(vet2) || vet1 == vet2) + if (!adjList.TryGetValue(vet1, out List? vectors1) + || !adjList.TryGetValue(vet2, out List? vectors2) + || vet1 == vet2) throw new InvalidOperationException(); // 删除边 vet1 - vet2 - adjList[vet1].Remove(vet2); - adjList[vet2].Remove(vet1); + vectors1.Remove(vet2); + vectors2.Remove(vet1); } /* 添加顶点 */ @@ -50,7 +53,7 @@ public void AddVertex(Vertex vet) { if (adjList.ContainsKey(vet)) return; // 在邻接表中添加一个新链表 - adjList.Add(vet, new List()); + adjList.Add(vet, []); } /* 删除顶点 */ @@ -69,7 +72,7 @@ public void RemoveVertex(Vertex vet) { public void Print() { Console.WriteLine("邻接表 ="); foreach (KeyValuePair> pair in adjList) { - List tmp = new(); + List tmp = []; foreach (Vertex vertex in pair.Value) tmp.Add(vertex.val); Console.WriteLine(pair.Key.val + ": [" + string.Join(", ", tmp) + "],"); @@ -81,10 +84,16 @@ public class graph_adjacency_list { [Test] public void Test() { /* 初始化无向图 */ - Vertex[] v = Vertex.ValsToVets(new int[] { 1, 3, 2, 5, 4 }); - Vertex[][] edges = new Vertex[][] { new Vertex[] { v[0], v[1] }, new Vertex[] { v[0], v[3] }, - new Vertex[] { v[1], v[2] }, new Vertex[] { v[2], v[3] }, - new Vertex[] { v[2], v[4] }, new Vertex[] { v[3], v[4] } }; + Vertex[] v = Vertex.ValsToVets([1, 3, 2, 5, 4]); + Vertex[][] edges = + [ + [v[0], v[1]], + [v[0], v[3]], + [v[1], v[2]], + [v[2], v[3]], + [v[2], v[4]], + [v[3], v[4]] + ]; GraphAdjList graph = new(edges); Console.WriteLine("\n初始化后,图为"); graph.Print(); diff --git a/codes/csharp/chapter_graph/graph_adjacency_matrix.cs b/codes/csharp/chapter_graph/graph_adjacency_matrix.cs index 751af2482e..22f7f6a6f2 100644 --- a/codes/csharp/chapter_graph/graph_adjacency_matrix.cs +++ b/codes/csharp/chapter_graph/graph_adjacency_matrix.cs @@ -13,8 +13,8 @@ class GraphAdjMat { /* 构造函数 */ public GraphAdjMat(int[] vertices, int[][] edges) { - this.vertices = new List(); - this.adjMat = new List>(); + this.vertices = []; + this.adjMat = []; // 添加顶点 foreach (int val in vertices) { AddVertex(val); @@ -97,10 +97,16 @@ public class graph_adjacency_matrix { public void Test() { /* 初始化无向图 */ // 请注意,edges 元素代表顶点索引,即对应 vertices 元素索引 - int[] vertices = { 1, 3, 2, 5, 4 }; - int[][] edges = new int[][] { new int[] { 0, 1 }, new int[] { 0, 3 }, - new int[] { 1, 2 }, new int[] { 2, 3 }, - new int[] { 2, 4 }, new int[] { 3, 4 } }; + int[] vertices = [1, 3, 2, 5, 4]; + int[][] edges = + [ + [0, 1], + [0, 3], + [1, 2], + [2, 3], + [2, 4], + [3, 4] + ]; GraphAdjMat graph = new(vertices, edges); Console.WriteLine("\n初始化后,图为"); graph.Print(); diff --git a/codes/csharp/chapter_graph/graph_bfs.cs b/codes/csharp/chapter_graph/graph_bfs.cs index 9b7c831ec0..70bf0799d6 100644 --- a/codes/csharp/chapter_graph/graph_bfs.cs +++ b/codes/csharp/chapter_graph/graph_bfs.cs @@ -11,9 +11,9 @@ public class graph_bfs { // 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点 public static List GraphBFS(GraphAdjList graph, Vertex startVet) { // 顶点遍历序列 - List res = new(); + List res = []; // 哈希表,用于记录已被访问过的顶点 - HashSet visited = new() { startVet }; + HashSet visited = [startVet]; // 队列用于实现 BFS Queue que = new(); que.Enqueue(startVet); @@ -37,14 +37,14 @@ public static List GraphBFS(GraphAdjList graph, Vertex startVet) { [Test] public void Test() { /* 初始化无向图 */ - Vertex[] v = Vertex.ValsToVets(new int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }); - Vertex[][] edges = new Vertex[12][] - { - new Vertex[2] { v[0], v[1] }, new Vertex[2] { v[0], v[3] }, new Vertex[2] { v[1], v[2] }, - new Vertex[2] { v[1], v[4] }, new Vertex[2] { v[2], v[5] }, new Vertex[2] { v[3], v[4] }, - new Vertex[2] { v[3], v[6] }, new Vertex[2] { v[4], v[5] }, new Vertex[2] { v[4], v[7] }, - new Vertex[2] { v[5], v[8] }, new Vertex[2] { v[6], v[7] }, new Vertex[2] { v[7], v[8] } - }; + Vertex[] v = Vertex.ValsToVets([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + Vertex[][] edges = + [ + [v[0], v[1]], [v[0], v[3]], [v[1], v[2]], + [v[1], v[4]], [v[2], v[5]], [v[3], v[4]], + [v[3], v[6]], [v[4], v[5]], [v[4], v[7]], + [v[5], v[8]], [v[6], v[7]], [v[7], v[8]] + ]; GraphAdjList graph = new(edges); Console.WriteLine("\n初始化后,图为"); diff --git a/codes/csharp/chapter_graph/graph_dfs.cs b/codes/csharp/chapter_graph/graph_dfs.cs index b1f9d9d370..e29cdff535 100644 --- a/codes/csharp/chapter_graph/graph_dfs.cs +++ b/codes/csharp/chapter_graph/graph_dfs.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_graph; public class graph_dfs { /* 深度优先遍历 DFS 辅助函数 */ - public void DFS(GraphAdjList graph, HashSet visited, List res, Vertex vet) { + public static void DFS(GraphAdjList graph, HashSet visited, List res, Vertex vet) { res.Add(vet); // 记录访问顶点 visited.Add(vet); // 标记该顶点已被访问 // 遍历该顶点的所有邻接顶点 @@ -23,11 +23,11 @@ public void DFS(GraphAdjList graph, HashSet visited, List res, V /* 深度优先遍历 DFS */ // 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点 - public List GraphDFS(GraphAdjList graph, Vertex startVet) { + public static List GraphDFS(GraphAdjList graph, Vertex startVet) { // 顶点遍历序列 - List res = new(); + List res = []; // 哈希表,用于记录已被访问过的顶点 - HashSet visited = new(); + HashSet visited = []; DFS(graph, visited, res, startVet); return res; } @@ -35,12 +35,12 @@ public List GraphDFS(GraphAdjList graph, Vertex startVet) { [Test] public void Test() { /* 初始化无向图 */ - Vertex[] v = Vertex.ValsToVets(new int[7] { 0, 1, 2, 3, 4, 5, 6 }); - Vertex[][] edges = new Vertex[6][] - { - new Vertex[2] { v[0], v[1] }, new Vertex[2] { v[0], v[3] }, new Vertex[2] { v[1], v[2] }, - new Vertex[2] { v[2], v[5] }, new Vertex[2] { v[4], v[5] }, new Vertex[2] { v[5], v[6] }, - }; + Vertex[] v = Vertex.ValsToVets([0, 1, 2, 3, 4, 5, 6]); + Vertex[][] edges = + [ + [v[0], v[1]], [v[0], v[3]], [v[1], v[2]], + [v[2], v[5]], [v[4], v[5]], [v[5], v[6]], + ]; GraphAdjList graph = new(edges); Console.WriteLine("\n初始化后,图为"); diff --git a/codes/csharp/chapter_greedy/coin_change_greedy.cs b/codes/csharp/chapter_greedy/coin_change_greedy.cs index 1380d2fd6b..5707b9ef0b 100644 --- a/codes/csharp/chapter_greedy/coin_change_greedy.cs +++ b/codes/csharp/chapter_greedy/coin_change_greedy.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_greedy; public class coin_change_greedy { /* 零钱兑换:贪心 */ - public int CoinChangeGreedy(int[] coins, int amt) { + public static int CoinChangeGreedy(int[] coins, int amt) { // 假设 coins 列表有序 int i = coins.Length - 1; int count = 0; @@ -29,14 +29,14 @@ public int CoinChangeGreedy(int[] coins, int amt) { [Test] public void Test() { // 贪心:能够保证找到全局最优解 - int[] coins = { 1, 5, 10, 20, 50, 100 }; + int[] coins = [1, 5, 10, 20, 50, 100]; int amt = 186; int res = CoinChangeGreedy(coins, amt); Console.WriteLine("\ncoins = " + coins.PrintList() + ", amt = " + amt); Console.WriteLine("凑到 " + amt + " 所需的最少硬币数量为 " + res); // 贪心:无法保证找到全局最优解 - coins = new int[] { 1, 20, 50 }; + coins = [1, 20, 50]; amt = 60; res = CoinChangeGreedy(coins, amt); Console.WriteLine("\ncoins = " + coins.PrintList() + ", amt = " + amt); @@ -44,7 +44,7 @@ public void Test() { Console.WriteLine("实际上需要的最少数量为 3 ,即 20 + 20 + 20"); // 贪心:无法保证找到全局最优解 - coins = new int[] { 1, 49, 50 }; + coins = [1, 49, 50]; amt = 98; res = CoinChangeGreedy(coins, amt); Console.WriteLine("\ncoins = " + coins.PrintList() + ", amt = " + amt); diff --git a/codes/csharp/chapter_greedy/fractional_knapsack.cs b/codes/csharp/chapter_greedy/fractional_knapsack.cs index 9e15690d73..253afe3a3c 100644 --- a/codes/csharp/chapter_greedy/fractional_knapsack.cs +++ b/codes/csharp/chapter_greedy/fractional_knapsack.cs @@ -7,19 +7,14 @@ namespace hello_algo.chapter_greedy; /* 物品 */ -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; // 物品价值 } public class fractional_knapsack { /* 分数背包:贪心 */ - public double FractionalKnapsack(int[] wgt, int[] val, int cap) { + public static double FractionalKnapsack(int[] wgt, int[] val, int cap) { // 创建物品列表,包含两个属性:重量、价值 Item[] items = new Item[wgt.Length]; for (int i = 0; i < wgt.Length; i++) { @@ -46,8 +41,8 @@ public double FractionalKnapsack(int[] wgt, int[] val, int cap) { [Test] public void Test() { - int[] wgt = { 10, 20, 30, 40, 50 }; - int[] val = { 50, 120, 150, 210, 240 }; + int[] wgt = [10, 20, 30, 40, 50]; + int[] val = [50, 120, 150, 210, 240]; int cap = 50; // 贪心算法 diff --git a/codes/csharp/chapter_greedy/max_capacity.cs b/codes/csharp/chapter_greedy/max_capacity.cs index 9e579212ee..5f11fca3f2 100644 --- a/codes/csharp/chapter_greedy/max_capacity.cs +++ b/codes/csharp/chapter_greedy/max_capacity.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_greedy; public class max_capacity { /* 最大容量:贪心 */ - public int MaxCapacity(int[] ht) { + public static int MaxCapacity(int[] ht) { // 初始化 i, j 分列数组两端 int i = 0, j = ht.Length - 1; // 初始最大容量为 0 @@ -30,7 +30,7 @@ public int MaxCapacity(int[] ht) { [Test] public void Test() { - int[] ht = { 3, 8, 5, 2, 7, 7, 3, 4 }; + int[] ht = [3, 8, 5, 2, 7, 7, 3, 4]; // 贪心算法 int res = MaxCapacity(ht); diff --git a/codes/csharp/chapter_greedy/max_product_cutting.cs b/codes/csharp/chapter_greedy/max_product_cutting.cs index 9eb143e0bc..1b5c62fa35 100644 --- a/codes/csharp/chapter_greedy/max_product_cutting.cs +++ b/codes/csharp/chapter_greedy/max_product_cutting.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_greedy; public class max_product_cutting { /* 最大切分乘积:贪心 */ - public int MaxProductCutting(int n) { + public static int MaxProductCutting(int n) { // 当 n <= 3 时,必须切分出一个 1 if (n <= 3) { return 1 * (n - 1); diff --git a/codes/csharp/chapter_hashing/array_hash_map.cs b/codes/csharp/chapter_hashing/array_hash_map.cs index e994566ef5..5df489d279 100644 --- a/codes/csharp/chapter_hashing/array_hash_map.cs +++ b/codes/csharp/chapter_hashing/array_hash_map.cs @@ -7,13 +7,9 @@ namespace hello_algo.chapter_hashing; /* 键值对 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; } /* 基于数组简易实现的哈希表 */ @@ -21,14 +17,14 @@ class ArrayHashMap { private readonly List buckets; public ArrayHashMap() { // 初始化数组,包含 100 个桶 - buckets = new(); + buckets = []; for (int i = 0; i < 100; i++) { buckets.Add(null); } } /* 哈希函数 */ - private int HashFunc(int key) { + private static int HashFunc(int key) { int index = key % 100; return index; } @@ -57,7 +53,7 @@ public void Remove(int key) { /* 获取所有键值对 */ public List PairSet() { - List pairSet = new(); + List pairSet = []; foreach (Pair? pair in buckets) { if (pair != null) pairSet.Add(pair); @@ -67,7 +63,7 @@ public List PairSet() { /* 获取所有键 */ public List KeySet() { - List keySet = new(); + List keySet = []; foreach (Pair? pair in buckets) { if (pair != null) keySet.Add(pair.key); @@ -77,7 +73,7 @@ public List KeySet() { /* 获取所有值 */ public List ValueSet() { - List valueSet = new(); + List valueSet = []; foreach (Pair? pair in buckets) { if (pair != null) valueSet.Add(pair.val); diff --git a/codes/csharp/chapter_hashing/built_in_hash.cs b/codes/csharp/chapter_hashing/built_in_hash.cs index 513cc9c331..2f7c0e7513 100644 --- a/codes/csharp/chapter_hashing/built_in_hash.cs +++ b/codes/csharp/chapter_hashing/built_in_hash.cs @@ -25,7 +25,7 @@ public void Test() { int hashStr = str.GetHashCode(); Console.WriteLine("字符串 " + str + " 的哈希值为 " + hashStr); - object[] arr = { 12836, "小哈" }; + object[] arr = [12836, "小哈"]; int hashTup = arr.GetHashCode(); Console.WriteLine("数组 [" + string.Join(", ", arr) + "] 的哈希值为 " + hashTup); diff --git a/codes/csharp/chapter_hashing/hash_map_chaining.cs b/codes/csharp/chapter_hashing/hash_map_chaining.cs index b4ab0eec40..bd9c39758f 100644 --- a/codes/csharp/chapter_hashing/hash_map_chaining.cs +++ b/codes/csharp/chapter_hashing/hash_map_chaining.cs @@ -22,7 +22,7 @@ public HashMapChaining() { extendRatio = 2; buckets = new List>(capacity); for (int i = 0; i < capacity; i++) { - buckets.Add(new List()); + buckets.Add([]); } } @@ -89,7 +89,7 @@ private void Extend() { capacity *= extendRatio; buckets = new List>(capacity); for (int i = 0; i < capacity; i++) { - buckets.Add(new List()); + buckets.Add([]); } size = 0; // 将键值对从原哈希表搬运至新哈希表 @@ -103,7 +103,7 @@ private void Extend() { /* 打印哈希表 */ public void Print() { foreach (List bucket in buckets) { - List res = new(); + List res = []; foreach (Pair pair in bucket) { res.Add(pair.key + " -> " + pair.val); } diff --git a/codes/csharp/chapter_heap/heap.cs b/codes/csharp/chapter_heap/heap.cs index 1b644a1c87..c2b916fcf9 100644 --- a/codes/csharp/chapter_heap/heap.cs +++ b/codes/csharp/chapter_heap/heap.cs @@ -7,13 +7,13 @@ namespace hello_algo.chapter_heap; public class heap { - public void TestPush(PriorityQueue heap, int val) { + public static void TestPush(PriorityQueue heap, int val) { heap.Enqueue(val, val); // 元素入堆 Console.WriteLine($"\n元素 {val} 入堆后\n"); PrintUtil.PrintHeap(heap); } - public void TestPop(PriorityQueue heap) { + public static void TestPop(PriorityQueue heap) { int val = heap.Dequeue(); // 堆顶元素出堆 Console.WriteLine($"\n堆顶元素 {val} 出堆后\n"); PrintUtil.PrintHeap(heap); diff --git a/codes/csharp/chapter_heap/my_heap.cs b/codes/csharp/chapter_heap/my_heap.cs index 2f47bb33ff..da2d5e9083 100644 --- a/codes/csharp/chapter_heap/my_heap.cs +++ b/codes/csharp/chapter_heap/my_heap.cs @@ -13,7 +13,7 @@ class MaxHeap { /* 构造函数,建立空堆 */ public MaxHeap() { - maxHeap = new List(); + maxHeap = []; } /* 构造函数,根据输入列表建堆 */ @@ -28,17 +28,17 @@ public MaxHeap(IEnumerable nums) { } /* 获取左子节点索引 */ - int Left(int i) { + static int Left(int i) { return 2 * i + 1; } /* 获取右子节点索引 */ - int Right(int i) { + static int Right(int i) { return 2 * i + 2; } /* 获取父节点索引 */ - int Parent(int i) { + static int Parent(int i) { return (i - 1) / 2; // 向下整除 } @@ -130,7 +130,7 @@ public class my_heap { [Test] public void Test() { /* 初始化大顶堆 */ - MaxHeap maxHeap = new(new int[] { 9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2 }); + MaxHeap maxHeap = new([9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2]); Console.WriteLine("\n输入列表并建堆后"); maxHeap.Print(); diff --git a/codes/csharp/chapter_heap/top_k.cs b/codes/csharp/chapter_heap/top_k.cs index 90460e1f87..9427feff9a 100644 --- a/codes/csharp/chapter_heap/top_k.cs +++ b/codes/csharp/chapter_heap/top_k.cs @@ -28,7 +28,7 @@ public static PriorityQueue TopKHeap(int[] nums, int k) { [Test] public void Test() { - int[] nums = { 1, 7, 6, 3, 2 }; + int[] nums = [1, 7, 6, 3, 2]; int k = 3; PriorityQueue res = TopKHeap(nums, k); Console.WriteLine("最大的 " + k + " 个元素为"); diff --git a/codes/csharp/chapter_searching/binary_search.cs b/codes/csharp/chapter_searching/binary_search.cs index 03453f558e..9c7933330a 100644 --- a/codes/csharp/chapter_searching/binary_search.cs +++ b/codes/csharp/chapter_searching/binary_search.cs @@ -46,7 +46,7 @@ static int BinarySearchLCRO(int[] nums, int target) { [Test] public void Test() { int target = 6; - int[] nums = { 1, 3, 6, 8, 12, 15, 23, 26, 31, 35 }; + int[] nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35]; /* 二分查找(双闭区间) */ int index = BinarySearch(nums, target); diff --git a/codes/csharp/chapter_searching/binary_search_edge.cs b/codes/csharp/chapter_searching/binary_search_edge.cs index 79a029f0c7..cc880857b4 100644 --- a/codes/csharp/chapter_searching/binary_search_edge.cs +++ b/codes/csharp/chapter_searching/binary_search_edge.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_searching; public class binary_search_edge { /* 二分查找最左一个 target */ - public int BinarySearchLeftEdge(int[] nums, int target) { + public static int BinarySearchLeftEdge(int[] nums, int target) { // 等价于查找 target 的插入点 int i = binary_search_insertion.BinarySearchInsertion(nums, target); // 未找到 target ,返回 -1 @@ -20,7 +20,7 @@ public int BinarySearchLeftEdge(int[] nums, int target) { } /* 二分查找最右一个 target */ - public int BinarySearchRightEdge(int[] nums, int target) { + public static int BinarySearchRightEdge(int[] nums, int target) { // 转化为查找最左一个 target + 1 int i = binary_search_insertion.BinarySearchInsertion(nums, target + 1); // j 指向最右一个 target ,i 指向首个大于 target 的元素 @@ -36,7 +36,7 @@ public int BinarySearchRightEdge(int[] nums, int target) { [Test] public void Test() { // 包含重复元素的数组 - int[] nums = { 1, 3, 6, 6, 6, 6, 6, 10, 12, 15 }; + int[] nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15]; Console.WriteLine("\n数组 nums = " + nums.PrintList()); // 二分查找左边界和右边界 diff --git a/codes/csharp/chapter_searching/binary_search_insertion.cs b/codes/csharp/chapter_searching/binary_search_insertion.cs index 00331c0608..af4c1d21f8 100644 --- a/codes/csharp/chapter_searching/binary_search_insertion.cs +++ b/codes/csharp/chapter_searching/binary_search_insertion.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_searching; public class binary_search_insertion { /* 二分查找插入点(无重复元素) */ - public int BinarySearchInsertionSimple(int[] nums, int target) { + public static 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 @@ -44,7 +44,7 @@ public static int BinarySearchInsertion(int[] nums, int target) { [Test] public void Test() { // 无重复元素的数组 - int[] nums = { 1, 3, 6, 8, 12, 15, 23, 26, 31, 35 }; + int[] nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35]; Console.WriteLine("\n数组 nums = " + nums.PrintList()); // 二分查找插入点 foreach (int target in new int[] { 6, 9 }) { @@ -53,7 +53,7 @@ public void Test() { } // 包含重复元素的数组 - nums = new int[] { 1, 3, 6, 6, 6, 6, 6, 10, 12, 15 }; + nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15]; Console.WriteLine("\n数组 nums = " + nums.PrintList()); // 二分查找插入点 foreach (int target in new int[] { 2, 6, 20 }) { diff --git a/codes/csharp/chapter_searching/hashing_search.cs b/codes/csharp/chapter_searching/hashing_search.cs index c8a177254b..4e1717c606 100644 --- a/codes/csharp/chapter_searching/hashing_search.cs +++ b/codes/csharp/chapter_searching/hashing_search.cs @@ -27,9 +27,9 @@ public void Test() { int target = 3; /* 哈希查找(数组) */ - int[] nums = { 1, 5, 3, 2, 4, 7, 5, 9, 10, 8 }; + int[] nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8]; // 初始化哈希表 - Dictionary map = new(); + Dictionary map = []; for (int i = 0; i < nums.Length; i++) { map[nums[i]] = i; // key: 元素,value: 索引 } @@ -39,7 +39,7 @@ public void Test() { /* 哈希查找(链表) */ ListNode? head = ListNode.ArrToLinkedList(nums); // 初始化哈希表 - Dictionary map1 = new(); + Dictionary map1 = []; while (head != null) { map1[head.val] = head; // key: 节点值,value: 节点 head = head.next; diff --git a/codes/csharp/chapter_searching/linear_search.cs b/codes/csharp/chapter_searching/linear_search.cs index 03fc49a747..26ee5b2863 100644 --- a/codes/csharp/chapter_searching/linear_search.cs +++ b/codes/csharp/chapter_searching/linear_search.cs @@ -37,7 +37,7 @@ public void Test() { int target = 3; /* 在数组中执行线性查找 */ - int[] nums = { 1, 5, 3, 2, 4, 7, 5, 9, 10, 8 }; + int[] nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8]; int index = LinearSearchArray(nums, target); Console.WriteLine("目标元素 3 的索引 = " + index); diff --git a/codes/csharp/chapter_searching/two_sum.cs b/codes/csharp/chapter_searching/two_sum.cs index 70f4d21fc7..1cfbe6918a 100644 --- a/codes/csharp/chapter_searching/two_sum.cs +++ b/codes/csharp/chapter_searching/two_sum.cs @@ -14,31 +14,31 @@ public static int[] TwoSumBruteForce(int[] nums, int target) { 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(); + return []; } /* 方法二:辅助哈希表 */ public static int[] TwoSumHashTable(int[] nums, int target) { int size = nums.Length; // 辅助哈希表,空间复杂度 O(n) - Dictionary dic = new(); + Dictionary 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(); + return []; } [Test] public void Test() { // ======= Test Case ======= - int[] nums = { 2, 7, 11, 15 }; + int[] nums = [2, 7, 11, 15]; int target = 13; // ====== Driver Code ====== diff --git a/codes/csharp/chapter_sorting/bubble_sort.cs b/codes/csharp/chapter_sorting/bubble_sort.cs index 914f4bbd7a..bb4db09648 100644 --- a/codes/csharp/chapter_sorting/bubble_sort.cs +++ b/codes/csharp/chapter_sorting/bubble_sort.cs @@ -40,11 +40,11 @@ static void BubbleSortWithFlag(int[] nums) { [Test] public void Test() { - int[] nums = { 4, 1, 3, 1, 5, 2 }; + int[] nums = [4, 1, 3, 1, 5, 2]; BubbleSort(nums); Console.WriteLine("冒泡排序完成后 nums = " + string.Join(",", nums)); - int[] nums1 = { 4, 1, 3, 1, 5, 2 }; + int[] nums1 = [4, 1, 3, 1, 5, 2]; BubbleSortWithFlag(nums1); Console.WriteLine("冒泡排序完成后 nums1 = " + string.Join(",", nums1)); } diff --git a/codes/csharp/chapter_sorting/bucket_sort.cs b/codes/csharp/chapter_sorting/bucket_sort.cs index 2422656234..f95a0566eb 100644 --- a/codes/csharp/chapter_sorting/bucket_sort.cs +++ b/codes/csharp/chapter_sorting/bucket_sort.cs @@ -11,9 +11,9 @@ public class bucket_sort { public static void BucketSort(float[] nums) { // 初始化 k = n/2 个桶,预期向每个桶分配 2 个元素 int k = nums.Length / 2; - List> buckets = new(); + List> buckets = []; for (int i = 0; i < k; i++) { - buckets.Add(new List()); + buckets.Add([]); } // 1. 将数组元素分配到各个桶中 foreach (float num in nums) { @@ -39,7 +39,7 @@ public static void BucketSort(float[] nums) { [Test] public void Test() { // 设输入数据为浮点数,范围为 [0, 1) - float[] nums = { 0.49f, 0.96f, 0.82f, 0.09f, 0.57f, 0.43f, 0.91f, 0.75f, 0.15f, 0.37f }; + float[] nums = [0.49f, 0.96f, 0.82f, 0.09f, 0.57f, 0.43f, 0.91f, 0.75f, 0.15f, 0.37f]; BucketSort(nums); Console.WriteLine("桶排序完成后 nums = " + string.Join(" ", nums)); } diff --git a/codes/csharp/chapter_sorting/counting_sort.cs b/codes/csharp/chapter_sorting/counting_sort.cs index 5930aef7f7..f2f7689823 100644 --- a/codes/csharp/chapter_sorting/counting_sort.cs +++ b/codes/csharp/chapter_sorting/counting_sort.cs @@ -66,11 +66,11 @@ static void CountingSort(int[] nums) { [Test] public void Test() { - int[] nums = { 1, 0, 1, 2, 0, 4, 0, 2, 2, 4 }; + int[] nums = [1, 0, 1, 2, 0, 4, 0, 2, 2, 4]; CountingSortNaive(nums); Console.WriteLine("计数排序(无法排序对象)完成后 nums = " + string.Join(" ", nums)); - int[] nums1 = { 1, 0, 1, 2, 0, 4, 0, 2, 2, 4 }; + int[] nums1 = [1, 0, 1, 2, 0, 4, 0, 2, 2, 4]; CountingSort(nums1); Console.WriteLine("计数排序完成后 nums1 = " + string.Join(" ", nums)); } diff --git a/codes/csharp/chapter_sorting/heap_sort.cs b/codes/csharp/chapter_sorting/heap_sort.cs index 9c57cf6fab..b70adecd7f 100644 --- a/codes/csharp/chapter_sorting/heap_sort.cs +++ b/codes/csharp/chapter_sorting/heap_sort.cs @@ -45,7 +45,7 @@ public static void HeapSort(int[] nums) { [Test] public void Test() { - int[] nums = { 4, 1, 3, 1, 5, 2 }; + int[] nums = [4, 1, 3, 1, 5, 2]; HeapSort(nums); Console.WriteLine("堆排序完成后 nums = " + string.Join(" ", nums)); } diff --git a/codes/csharp/chapter_sorting/insertion_sort.cs b/codes/csharp/chapter_sorting/insertion_sort.cs index 88fbda53f4..aefc89f4bf 100644 --- a/codes/csharp/chapter_sorting/insertion_sort.cs +++ b/codes/csharp/chapter_sorting/insertion_sort.cs @@ -23,7 +23,7 @@ static void InsertionSort(int[] nums) { [Test] public void Test() { - int[] nums = { 4, 1, 3, 1, 5, 2 }; + int[] nums = [4, 1, 3, 1, 5, 2]; InsertionSort(nums); Console.WriteLine("插入排序完成后 nums = " + string.Join(",", nums)); } diff --git a/codes/csharp/chapter_sorting/merge_sort.cs b/codes/csharp/chapter_sorting/merge_sort.cs index 907eb1f2ba..7d06d02bd7 100644 --- a/codes/csharp/chapter_sorting/merge_sort.cs +++ b/codes/csharp/chapter_sorting/merge_sort.cs @@ -49,7 +49,7 @@ static void MergeSort(int[] nums, int left, int right) { [Test] public void Test() { /* 归并排序 */ - int[] nums = { 7, 3, 2, 6, 0, 1, 5, 4 }; + int[] nums = [7, 3, 2, 6, 0, 1, 5, 4]; MergeSort(nums, 0, nums.Length - 1); Console.WriteLine("归并排序完成后 nums = " + string.Join(",", nums)); } diff --git a/codes/csharp/chapter_sorting/quick_sort.cs b/codes/csharp/chapter_sorting/quick_sort.cs index a482758488..bf43310435 100644 --- a/codes/csharp/chapter_sorting/quick_sort.cs +++ b/codes/csharp/chapter_sorting/quick_sort.cs @@ -135,17 +135,17 @@ public class quick_sort { [Test] public void Test() { /* 快速排序 */ - int[] nums = { 2, 4, 1, 0, 3, 5 }; + int[] nums = [2, 4, 1, 0, 3, 5]; quickSort.QuickSort(nums, 0, nums.Length - 1); Console.WriteLine("快速排序完成后 nums = " + string.Join(",", nums)); /* 快速排序(中位基准数优化) */ - int[] nums1 = { 2, 4, 1, 0, 3, 5 }; + int[] nums1 = [2, 4, 1, 0, 3, 5]; QuickSortMedian.QuickSort(nums1, 0, nums1.Length - 1); Console.WriteLine("快速排序(中位基准数优化)完成后 nums1 = " + string.Join(",", nums1)); /* 快速排序(尾递归优化) */ - int[] nums2 = { 2, 4, 1, 0, 3, 5 }; + int[] nums2 = [2, 4, 1, 0, 3, 5]; QuickSortTailCall.QuickSort(nums2, 0, nums2.Length - 1); Console.WriteLine("快速排序(尾递归优化)完成后 nums2 = " + string.Join(",", nums2)); } diff --git a/codes/csharp/chapter_sorting/radix_sort.cs b/codes/csharp/chapter_sorting/radix_sort.cs index efb2533cdc..e960071865 100644 --- a/codes/csharp/chapter_sorting/radix_sort.cs +++ b/codes/csharp/chapter_sorting/radix_sort.cs @@ -61,8 +61,8 @@ static void RadixSort(int[] nums) { [Test] public void Test() { // 基数排序 - int[] nums = { 10546151, 35663510, 42865989, 34862445, 81883077, - 88906420, 72429244, 30524779, 82060337, 63832996 }; + int[] nums = [ 10546151, 35663510, 42865989, 34862445, 81883077, + 88906420, 72429244, 30524779, 82060337, 63832996 ]; RadixSort(nums); Console.WriteLine("基数排序完成后 nums = " + string.Join(" ", nums)); } diff --git a/codes/csharp/chapter_sorting/selection_sort.cs b/codes/csharp/chapter_sorting/selection_sort.cs index 8db3b28cc3..4635a33f52 100644 --- a/codes/csharp/chapter_sorting/selection_sort.cs +++ b/codes/csharp/chapter_sorting/selection_sort.cs @@ -25,7 +25,7 @@ public static void SelectionSort(int[] nums) { [Test] public void Test() { - int[] nums = { 4, 1, 3, 1, 5, 2 }; + int[] nums = [4, 1, 3, 1, 5, 2]; SelectionSort(nums); Console.WriteLine("选择排序完成后 nums = " + string.Join(" ", nums)); } diff --git a/codes/csharp/chapter_stack_and_queue/array_stack.cs b/codes/csharp/chapter_stack_and_queue/array_stack.cs index d68c02eb1b..558efcaaf8 100644 --- a/codes/csharp/chapter_stack_and_queue/array_stack.cs +++ b/codes/csharp/chapter_stack_and_queue/array_stack.cs @@ -11,7 +11,7 @@ class ArrayStack { private readonly List stack; public ArrayStack() { // 初始化列表(动态数组) - stack = new(); + stack = []; } /* 获取栈的长度 */ @@ -47,7 +47,7 @@ public int Peek() { /* 将 List 转化为 Array 并返回 */ public int[] ToArray() { - return stack.ToArray(); + return [.. stack]; } } diff --git a/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs b/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs index 1b3962ce5b..51586fbc83 100644 --- a/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs +++ b/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs @@ -7,16 +7,10 @@ namespace hello_algo.chapter_stack_and_queue; /* 双向链表节点 */ -public class ListNode { - public int val; // 节点值 - public ListNode? next; // 后继节点引用 - public ListNode? prev; // 前驱节点引用 - - public ListNode(int val) { - this.val = val; - prev = null; - next = null; - } +public class ListNode(int val) { + public int val = val; // 节点值 + public ListNode? next = null; // 后继节点引用 + public ListNode? prev = null; // 前驱节点引用 } /* 基于双向链表实现的双向队列 */ @@ -50,14 +44,14 @@ private void Push(int num, bool isFront) { // 队首入队操作 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; // 更新尾节点 } @@ -87,7 +81,7 @@ public void PushLast(int num) { ListNode? fNext = front?.next; if (fNext != null) { fNext.prev = null; - front.next = null; + front!.next = null; } front = fNext; // 更新头节点 } @@ -98,7 +92,7 @@ public void PushLast(int num) { ListNode? rPrev = rear?.prev; if (rPrev != null) { rPrev.next = null; - rear.prev = null; + rear!.prev = null; } rear = rPrev; // 更新尾节点 } diff --git a/codes/csharp/chapter_stack_and_queue/linkedlist_queue.cs b/codes/csharp/chapter_stack_and_queue/linkedlist_queue.cs index e4ab90aa4b..37bb3a21cb 100644 --- a/codes/csharp/chapter_stack_and_queue/linkedlist_queue.cs +++ b/codes/csharp/chapter_stack_and_queue/linkedlist_queue.cs @@ -55,18 +55,18 @@ public int Pop() { public int Peek() { if (IsEmpty()) throw new Exception(); - return front.val; + return front!.val; } /* 将链表转化为 Array 并返回 */ public int[] ToArray() { if (front == null) - return Array.Empty(); + 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; diff --git a/codes/csharp/chapter_stack_and_queue/linkedlist_stack.cs b/codes/csharp/chapter_stack_and_queue/linkedlist_stack.cs index 74879099b9..ab5c058a98 100644 --- a/codes/csharp/chapter_stack_and_queue/linkedlist_stack.cs +++ b/codes/csharp/chapter_stack_and_queue/linkedlist_stack.cs @@ -37,7 +37,7 @@ public void Push(int num) { /* 出栈 */ public int Pop() { int num = Peek(); - stackPeek = stackPeek.next; + stackPeek = stackPeek!.next; stkSize--; return num; } @@ -46,18 +46,18 @@ public int Pop() { 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(); + 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; diff --git a/codes/csharp/chapter_tree/array_binary_tree.cs b/codes/csharp/chapter_tree/array_binary_tree.cs index 7c1aba9a2e..76dcd6d078 100644 --- a/codes/csharp/chapter_tree/array_binary_tree.cs +++ b/codes/csharp/chapter_tree/array_binary_tree.cs @@ -7,13 +7,8 @@ namespace hello_algo.chapter_tree; /* 数组表示下的二叉树类 */ -public class ArrayBinaryTree { - private readonly List tree; - - /* 构造方法 */ - public ArrayBinaryTree(List arr) { - tree = new List(arr); - } +public class ArrayBinaryTree(List arr) { + private readonly List tree = new(arr); /* 节点数量 */ public int Size() { @@ -29,27 +24,27 @@ public int Size() { } /* 获取索引为 i 节点的左子节点的索引 */ - public int Left(int i) { + public static int Left(int i) { return 2 * i + 1; } /* 获取索引为 i 节点的右子节点的索引 */ - public int Right(int i) { + public static int Right(int i) { return 2 * i + 2; } /* 获取索引为 i 节点的父节点的索引 */ - public int Parent(int i) { + public static int Parent(int i) { return (i - 1) / 2; } /* 层序遍历 */ public List LevelOrder() { - List res = new(); + List res = []; // 直接遍历数组 for (int i = 0; i < Size(); i++) { if (Val(i).HasValue) - res.Add(Val(i).Value); + res.Add(Val(i)!.Value); } return res; } @@ -61,34 +56,34 @@ private void DFS(int i, string order, List res) { 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 PreOrder() { - List res = new(); + List res = []; DFS(0, "pre", res); return res; } /* 中序遍历 */ public List InOrder() { - List res = new(); + List res = []; DFS(0, "in", res); return res; } /* 后序遍历 */ public List PostOrder() { - List res = new(); + List res = []; DFS(0, "post", res); return res; } @@ -99,9 +94,9 @@ public class array_binary_tree { public void Test() { // 初始化二叉树 // 这里借助了一个从数组直接生成二叉树的函数 - List arr = new() { 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 }; + List arr = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; - TreeNode root = TreeNode.ListToTree(arr); + TreeNode? root = TreeNode.ListToTree(arr); Console.WriteLine("\n初始化二叉树\n"); Console.WriteLine("二叉树的数组表示:"); Console.WriteLine(arr.PrintList()); @@ -113,9 +108,9 @@ public void Test() { // 访问节点 int i = 1; - int l = abt.Left(i); - int r = abt.Right(i); - int p = abt.Parent(i); + int l = ArrayBinaryTree.Left(i); + int r = ArrayBinaryTree.Right(i); + int p = ArrayBinaryTree.Parent(i); Console.WriteLine("\n当前节点的索引为 " + i + " ,值为 " + abt.Val(i)); Console.WriteLine("其左子节点的索引为 " + l + " ,值为 " + (abt.Val(l).HasValue ? abt.Val(l) : "null")); Console.WriteLine("其右子节点的索引为 " + r + " ,值为 " + (abt.Val(r).HasValue ? abt.Val(r) : "null")); diff --git a/codes/csharp/chapter_tree/avl_tree.cs b/codes/csharp/chapter_tree/avl_tree.cs index cceab16d01..1a072c00e9 100644 --- a/codes/csharp/chapter_tree/avl_tree.cs +++ b/codes/csharp/chapter_tree/avl_tree.cs @@ -11,19 +11,19 @@ class AVLTree { public TreeNode? root; // 根节点 /* 获取节点高度 */ - public int Height(TreeNode? node) { + public static int Height(TreeNode? node) { // 空节点高度为 -1 ,叶节点高度为 0 return node == null ? -1 : node.height; } /* 更新节点高度 */ - private void UpdateHeight(TreeNode node) { + private static void UpdateHeight(TreeNode node) { // 节点高度等于最高子树高度 + 1 node.height = Math.Max(Height(node.left), Height(node.right)) + 1; } /* 获取平衡因子 */ - public int BalanceFactor(TreeNode? node) { + public static int BalanceFactor(TreeNode? node) { // 空节点平衡因子为 0 if (node == null) return 0; // 节点平衡因子 = 左子树高度 - 右子树高度 @@ -31,8 +31,8 @@ public int BalanceFactor(TreeNode? node) { } /* 右旋操作 */ - TreeNode? RightRotate(TreeNode? node) { - TreeNode? child = node.left; + static TreeNode? RightRotate(TreeNode? node) { + TreeNode? child = node?.left; TreeNode? grandChild = child?.right; // 以 child 为原点,将 node 向右旋转 child.right = node; @@ -45,8 +45,8 @@ public int BalanceFactor(TreeNode? node) { } /* 左旋操作 */ - TreeNode? LeftRotate(TreeNode? node) { - TreeNode? child = node.right; + static TreeNode? LeftRotate(TreeNode? node) { + TreeNode? child = node?.right; TreeNode? grandChild = child?.left; // 以 child 为原点,将 node 向左旋转 child.left = node; @@ -59,28 +59,28 @@ public int BalanceFactor(TreeNode? node) { } /* 执行旋转操作,使该子树重新恢复平衡 */ - TreeNode? Rotate(TreeNode? node) { + static TreeNode? Rotate(TreeNode? node) { // 获取节点 node 的平衡因子 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); } } @@ -94,7 +94,7 @@ public void Insert(int val) { } /* 递归插入节点(辅助方法) */ - private TreeNode? InsertHelper(TreeNode? node, int val) { + private static TreeNode? InsertHelper(TreeNode? node, int val) { if (node == null) return new TreeNode(val); /* 1. 查找插入位置,并插入节点 */ if (val < node.val) @@ -116,7 +116,7 @@ public void Remove(int val) { } /* 递归删除节点(辅助方法) */ - private TreeNode? RemoveHelper(TreeNode? node, int val) { + private static TreeNode? RemoveHelper(TreeNode? node, int val) { if (node == null) return null; /* 1. 查找节点,并删除之 */ if (val < node.val) @@ -138,7 +138,7 @@ public void Remove(int val) { 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; } } diff --git a/codes/csharp/chapter_tree/binary_search_tree.cs b/codes/csharp/chapter_tree/binary_search_tree.cs index 8ddd47c5cd..aa67605b84 100644 --- a/codes/csharp/chapter_tree/binary_search_tree.cs +++ b/codes/csharp/chapter_tree/binary_search_tree.cs @@ -99,7 +99,7 @@ public void Remove(int num) { 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; @@ -116,7 +116,7 @@ public void Remove(int num) { tmp = tmp.left; } // 递归删除节点 tmp - Remove(tmp.val); + Remove(tmp.val!.Value); // 用 tmp 覆盖 cur cur.val = tmp.val; } @@ -129,7 +129,7 @@ public void Test() { /* 初始化二叉搜索树 */ BinarySearchTree bst = new(); // 请注意,不同的插入顺序会生成不同的二叉树,该序列可以生成一个完美二叉树 - int[] nums = { 8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15 }; + int[] nums = [8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15]; foreach (int num in nums) { bst.Insert(num); } @@ -139,7 +139,7 @@ public void Test() { /* 查找节点 */ TreeNode? node = bst.Search(7); - Console.WriteLine("\n查找到的节点对象为 " + node + ",节点值 = " + node.val); + Console.WriteLine("\n查找到的节点对象为 " + node + ",节点值 = " + node?.val); /* 插入节点 */ bst.Insert(16); diff --git a/codes/csharp/chapter_tree/binary_tree_bfs.cs b/codes/csharp/chapter_tree/binary_tree_bfs.cs index b580a2aedb..84e247b366 100644 --- a/codes/csharp/chapter_tree/binary_tree_bfs.cs +++ b/codes/csharp/chapter_tree/binary_tree_bfs.cs @@ -9,15 +9,15 @@ namespace hello_algo.chapter_tree; public class binary_tree_bfs { /* 层序遍历 */ - public List LevelOrder(TreeNode root) { + public static List LevelOrder(TreeNode root) { // 初始化队列,加入根节点 Queue queue = new(); queue.Enqueue(root); // 初始化一个列表,用于保存遍历序列 - List list = new(); + List 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) @@ -30,11 +30,11 @@ public List LevelOrder(TreeNode root) { public void Test() { /* 初始化二叉树 */ // 这里借助了一个从数组直接生成二叉树的函数 - TreeNode? root = TreeNode.ListToTree(new List { 1, 2, 3, 4, 5, 6, 7 }); + TreeNode? root = TreeNode.ListToTree([1, 2, 3, 4, 5, 6, 7]); Console.WriteLine("\n初始化二叉树\n"); PrintUtil.PrintTree(root); - List list = LevelOrder(root); + List list = LevelOrder(root!); Console.WriteLine("\n层序遍历的节点打印序列 = " + string.Join(",", list)); } } diff --git a/codes/csharp/chapter_tree/binary_tree_dfs.cs b/codes/csharp/chapter_tree/binary_tree_dfs.cs index 8f91c3b71e..8ff316d9be 100644 --- a/codes/csharp/chapter_tree/binary_tree_dfs.cs +++ b/codes/csharp/chapter_tree/binary_tree_dfs.cs @@ -7,13 +7,13 @@ namespace hello_algo.chapter_tree; public class binary_tree_dfs { - readonly List list = new(); + readonly List list = []; /* 前序遍历 */ void PreOrder(TreeNode? root) { if (root == null) return; // 访问优先级:根节点 -> 左子树 -> 右子树 - list.Add(root.val); + list.Add(root.val!.Value); PreOrder(root.left); PreOrder(root.right); } @@ -23,7 +23,7 @@ void InOrder(TreeNode? root) { if (root == null) return; // 访问优先级:左子树 -> 根节点 -> 右子树 InOrder(root.left); - list.Add(root.val); + list.Add(root.val!.Value); InOrder(root.right); } @@ -33,14 +33,14 @@ void PostOrder(TreeNode? root) { // 访问优先级:左子树 -> 右子树 -> 根节点 PostOrder(root.left); PostOrder(root.right); - list.Add(root.val); + list.Add(root.val!.Value); } [Test] public void Test() { /* 初始化二叉树 */ // 这里借助了一个从数组直接生成二叉树的函数 - TreeNode? root = TreeNode.ListToTree(new List { 1, 2, 3, 4, 5, 6, 7 }); + TreeNode? root = TreeNode.ListToTree([1, 2, 3, 4, 5, 6, 7]); Console.WriteLine("\n初始化二叉树\n"); PrintUtil.PrintTree(root); diff --git a/codes/csharp/hello-algo.csproj b/codes/csharp/hello-algo.csproj index 45cb9a39eb..43817cc382 100644 --- a/codes/csharp/hello-algo.csproj +++ b/codes/csharp/hello-algo.csproj @@ -2,17 +2,20 @@ Exe - net6.0 + net8.0 hello_algo enable enable - - - - + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/codes/csharp/utils/ListNode.cs b/codes/csharp/utils/ListNode.cs index 1e5e2134e0..430549815a 100644 --- a/codes/csharp/utils/ListNode.cs +++ b/codes/csharp/utils/ListNode.cs @@ -5,14 +5,10 @@ namespace hello_algo.utils; /* Definition for a singly-linked list node */ -public class ListNode { - public int val; +public class ListNode(int x) { + public int val = x; public ListNode? next; - public ListNode(int x) { - val = x; - } - /* Generate a linked list with an array */ public static ListNode? ArrToLinkedList(int[] arr) { ListNode dum = new(0); @@ -33,7 +29,7 @@ public ListNode(int x) { } public override string? ToString() { - List list = new(); + List list = []; var head = this; while (head != null) { list.Add(head.val.ToString()); diff --git a/codes/csharp/utils/PrintUtil.cs b/codes/csharp/utils/PrintUtil.cs index 6ee7f91446..97870b1af7 100644 --- a/codes/csharp/utils/PrintUtil.cs +++ b/codes/csharp/utils/PrintUtil.cs @@ -6,14 +6,9 @@ namespace hello_algo.utils; -public class Trunk { - public Trunk? prev; - public string str; - - public Trunk(Trunk? prev, string str) { - this.prev = prev; - this.str = str; - } +public class Trunk(Trunk? prev, string str) { + public Trunk? prev = prev; + public string str = str; }; public static class PrintUtil { @@ -45,8 +40,8 @@ public static void PrintMatrix(List> matrix) { } /* Print a linked list */ - public static void PrintLinkedList(ListNode head) { - List list = new(); + public static void PrintLinkedList(ListNode? head) { + List list = []; while (head != null) { list.Add(head.val.ToString()); head = head.next; @@ -115,10 +110,10 @@ public static void PrintHashMap(Dictionary map) where K : notnull { /* Print a heap */ public static void PrintHeap(Queue queue) { Console.Write("堆的数组表示:"); - List list = queue.ToList(); + List list = [.. queue]; Console.WriteLine(string.Join(',', list)); Console.WriteLine("堆的树状表示:"); - TreeNode tree = TreeNode.ListToTree(list.Cast().ToList()); + TreeNode? tree = TreeNode.ListToTree(list.Cast().ToList()); PrintTree(tree); } @@ -126,13 +121,13 @@ public static void PrintHeap(Queue queue) { public static void PrintHeap(PriorityQueue queue) { var newQueue = new PriorityQueue(queue.UnorderedItems, queue.Comparer); Console.Write("堆的数组表示:"); - List list = new(); + List list = []; while (newQueue.TryDequeue(out int element, out _)) { list.Add(element); } Console.WriteLine("堆的树状表示:"); Console.WriteLine(string.Join(',', list.ToList())); - TreeNode tree = TreeNode.ListToTree(list.Cast().ToList()); + TreeNode? tree = TreeNode.ListToTree(list.Cast().ToList()); PrintTree(tree); } } \ No newline at end of file diff --git a/codes/csharp/utils/TreeNode.cs b/codes/csharp/utils/TreeNode.cs index e18a2ccf0d..32e628a977 100644 --- a/codes/csharp/utils/TreeNode.cs +++ b/codes/csharp/utils/TreeNode.cs @@ -7,17 +7,12 @@ namespace hello_algo.utils; /* 二叉树节点类 */ -public class TreeNode { - public int val; // 节点值 +public class TreeNode(int? x) { + public int? val = x; // 节点值 public int height; // 节点高度 public TreeNode? left; // 左子节点引用 public TreeNode? right; // 右子节点引用 - /* 构造方法 */ - public TreeNode(int x) { - val = x; - } - // 序列化编码规则请参考: // https://www.hello-algo.com/chapter_tree/array_representation_of_tree/ // 二叉树的数组表示: @@ -39,7 +34,7 @@ public TreeNode(int x) { if (i < 0 || i >= arr.Count || !arr[i].HasValue) { return null; } - TreeNode root = new(arr[i].Value) { + TreeNode root = new(arr[i]) { left = ListToTreeDFS(arr, 2 * i + 1), right = ListToTreeDFS(arr, 2 * i + 2) }; @@ -65,7 +60,7 @@ private static void TreeToListDFS(TreeNode? root, int i, List res) { /* 将二叉树序列化为列表 */ public static List TreeToList(TreeNode root) { - List res = new(); + List res = []; TreeToListDFS(root, 0, res); return res; } diff --git a/codes/csharp/utils/Vertex.cs b/codes/csharp/utils/Vertex.cs index 0616fbe84d..b9672ef64d 100644 --- a/codes/csharp/utils/Vertex.cs +++ b/codes/csharp/utils/Vertex.cs @@ -7,11 +7,8 @@ namespace hello_algo.utils; /* 顶点类 */ -public class Vertex { - public int val; - public Vertex(int val) { - this.val = val; - } +public class Vertex(int val) { + public int val = val; /* 输入值列表 vals ,返回顶点列表 vets */ public static Vertex[] ValsToVets(int[] vals) { @@ -24,7 +21,7 @@ public static Vertex[] ValsToVets(int[] vals) { /* 输入顶点列表 vets ,返回值列表 vals */ public static List VetsToVals(List vets) { - List vals = new(); + List vals = []; foreach (Vertex vet in vets) { vals.Add(vet.val); } From 6751691c763b1094ebf3f158d500fa1e57a3c01e Mon Sep 17 00:00:00 2001 From: hpstory <354195783@qq.com> Date: Fri, 24 Nov 2023 16:33:54 +0800 Subject: [PATCH 02/10] update docs --- .github/workflows/dotnet.yml | 2 +- codes/Dockerfile | 4 +--- codes/csharp/utils/TreeNode.cs | 4 ++-- docs/chapter_array_and_linkedlist/array.md | 2 +- docs/chapter_array_and_linkedlist/linked_list.md | 12 +++++------- docs/chapter_array_and_linkedlist/list.md | 8 ++++---- .../space_complexity.md | 7 +++---- docs/chapter_hashing/hash_algorithm.md | 2 +- docs/chapter_heap/heap.md | 2 +- docs/chapter_tree/array_representation_of_tree.md | 2 +- docs/chapter_tree/avl_tree.md | 11 +++++------ docs/chapter_tree/binary_tree.md | 9 ++++----- 12 files changed, 29 insertions(+), 36 deletions(-) diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index 6383f08a9a..7001048c1c 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -22,7 +22,7 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] - dotnet-version: ["6.0.x"] + dotnet-version: ["8.0.x"] steps: - uses: actions/checkout@v4 diff --git a/codes/Dockerfile b/codes/Dockerfile index 310d91cb76..331ad599e6 100644 --- a/codes/Dockerfile +++ b/codes/Dockerfile @@ -19,10 +19,8 @@ RUN for LANG in $LANGS; do \ java) \ apt-get install -y openjdk-17-jdk ;; \ csharp) \ - wget https://packages.microsoft.com/config/ubuntu/20.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb && \ - dpkg -i packages-microsoft-prod.deb && \ apt-get update && \ - apt-get install -y dotnet-sdk-6.0 ;; \ + apt-get install -y dotnet-sdk-8.0 ;; \ # More languages... *) \ echo "Warning: No installation workflow for $LANG" ;; \ diff --git a/codes/csharp/utils/TreeNode.cs b/codes/csharp/utils/TreeNode.cs index 32e628a977..6d3ba46358 100644 --- a/codes/csharp/utils/TreeNode.cs +++ b/codes/csharp/utils/TreeNode.cs @@ -8,8 +8,8 @@ namespace hello_algo.utils; /* 二叉树节点类 */ public class TreeNode(int? x) { - public int? val = x; // 节点值 - public int height; // 节点高度 + public int? val = x; // 节点值 + public int height; // 节点高度 public TreeNode? left; // 左子节点引用 public TreeNode? right; // 右子节点引用 diff --git a/docs/chapter_array_and_linkedlist/array.md b/docs/chapter_array_and_linkedlist/array.md index 99a1bcb5a2..22dabbb9b5 100755 --- a/docs/chapter_array_and_linkedlist/array.md +++ b/docs/chapter_array_and_linkedlist/array.md @@ -43,7 +43,7 @@ ```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" diff --git a/docs/chapter_array_and_linkedlist/linked_list.md b/docs/chapter_array_and_linkedlist/linked_list.md index e485bb52d3..58a596942e 100755 --- a/docs/chapter_array_and_linkedlist/linked_list.md +++ b/docs/chapter_array_and_linkedlist/linked_list.md @@ -52,10 +52,9 @@ ```csharp title="" /* 链表节点类 */ - class ListNode { - int val; // 节点值 - ListNode next; // 指向下一节点的引用 - ListNode(int x) => val = x; //构造函数 + class ListNode(int x) { //构造函数 + int val = x; // 节点值 + ListNode? next; // 指向下一节点的引用 } ``` @@ -496,11 +495,10 @@ ```csharp title="" /* 双向链表节点类 */ - class ListNode { - int val; // 节点值 + class ListNode(int x) { // 构造函数 + int val = x; // 节点值 ListNode next; // 指向后继节点的引用 ListNode prev; // 指向前驱节点的引用 - ListNode(int x) => val = x; // 构造函数 } ``` diff --git a/docs/chapter_array_and_linkedlist/list.md b/docs/chapter_array_and_linkedlist/list.md index 0bf089993e..fe16455956 100755 --- a/docs/chapter_array_and_linkedlist/list.md +++ b/docs/chapter_array_and_linkedlist/list.md @@ -54,10 +54,10 @@ ```csharp title="list.cs" /* 初始化列表 */ // 无初始值 - List nums1 = new(); + List nums1 = []; // 有初始值 - int[] numbers = new int[] { 1, 3, 2, 5, 4 }; - List nums = numbers.ToList(); + int[] numbers = [1, 3, 2, 5, 4]; + List nums = [.. numbers]; ``` === "Go" @@ -700,7 +700,7 @@ ```csharp title="list.cs" /* 拼接两个列表 */ - List nums1 = new() { 6, 8, 7, 10, 9 }; + List nums1 = [6, 8, 7, 10, 9]; nums.AddRange(nums1); // 将列表 nums1 拼接到 nums 之后 ``` diff --git a/docs/chapter_computational_complexity/space_complexity.md b/docs/chapter_computational_complexity/space_complexity.md index b298d76fda..2b3e3c7a66 100755 --- a/docs/chapter_computational_complexity/space_complexity.md +++ b/docs/chapter_computational_complexity/space_complexity.md @@ -98,10 +98,9 @@ ```csharp title="" /* 类 */ - class Node { - int val; + class Node(int x) { + int val = x; Node next; - Node(int x) { val = x; } } /* 函数 */ @@ -113,7 +112,7 @@ 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; // 输出数据 } diff --git a/docs/chapter_hashing/hash_algorithm.md b/docs/chapter_hashing/hash_algorithm.md index 14099c64d1..1bd3b12da0 100644 --- a/docs/chapter_hashing/hash_algorithm.md +++ b/docs/chapter_hashing/hash_algorithm.md @@ -211,7 +211,7 @@ $$ int hashStr = str.GetHashCode(); // 字符串 Hello 算法 的哈希值为 -586107568; - object[] arr = { 12836, "小哈" }; + object[] arr = [12836, "小哈"]; int hashTup = arr.GetHashCode(); // 数组 [12836, 小哈] 的哈希值为 42931033; diff --git a/docs/chapter_heap/heap.md b/docs/chapter_heap/heap.md index 641a85ba09..c38e1839c6 100644 --- a/docs/chapter_heap/heap.md +++ b/docs/chapter_heap/heap.md @@ -187,7 +187,7 @@ bool isEmpty = maxHeap.Count == 0; /* 输入列表并建堆 */ - minHeap = new PriorityQueue(new List<(int, int)> { (1, 1), (3, 3), (2, 2), (5, 5), (4, 4), }); + minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); ``` === "Go" diff --git a/docs/chapter_tree/array_representation_of_tree.md b/docs/chapter_tree/array_representation_of_tree.md index cb9efcbef9..a1e1a4672f 100644 --- a/docs/chapter_tree/array_representation_of_tree.md +++ b/docs/chapter_tree/array_representation_of_tree.md @@ -53,7 +53,7 @@ ```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" diff --git a/docs/chapter_tree/avl_tree.md b/docs/chapter_tree/avl_tree.md index d397a1755b..e92e892624 100644 --- a/docs/chapter_tree/avl_tree.md +++ b/docs/chapter_tree/avl_tree.md @@ -63,12 +63,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; // 右子节点引用 } ``` diff --git a/docs/chapter_tree/binary_tree.md b/docs/chapter_tree/binary_tree.md index d01e82c31b..bfdb13237a 100644 --- a/docs/chapter_tree/binary_tree.md +++ b/docs/chapter_tree/binary_tree.md @@ -41,11 +41,10 @@ ```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; // 右子节点引用 } ``` From 326e110b1e8fb4741e027a2c053a7440d67bac2d Mon Sep 17 00:00:00 2001 From: hpstory <354195783@qq.com> Date: Fri, 24 Nov 2023 17:41:45 +0800 Subject: [PATCH 03/10] revert change --- codes/Dockerfile | 2 ++ 1 file changed, 2 insertions(+) diff --git a/codes/Dockerfile b/codes/Dockerfile index 331ad599e6..97d37bbcff 100644 --- a/codes/Dockerfile +++ b/codes/Dockerfile @@ -19,6 +19,8 @@ RUN for LANG in $LANGS; do \ java) \ apt-get install -y openjdk-17-jdk ;; \ csharp) \ + wget https://packages.microsoft.com/config/ubuntu/20.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb && \ + dpkg -i packages-microsoft-prod.deb && \ apt-get update && \ apt-get install -y dotnet-sdk-8.0 ;; \ # More languages... From e18f1d6b8424a7ac8b95e35262452a5a3dc1a718 Mon Sep 17 00:00:00 2001 From: peng han <354195783@qq.com> Date: Fri, 24 Nov 2023 21:06:15 +0800 Subject: [PATCH 04/10] revert change and update appendix docs --- codes/csharp/chapter_tree/array_binary_tree.cs | 12 ++++++------ docs/chapter_appendix/installation.md | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/codes/csharp/chapter_tree/array_binary_tree.cs b/codes/csharp/chapter_tree/array_binary_tree.cs index 76dcd6d078..aa2e0ba8b2 100644 --- a/codes/csharp/chapter_tree/array_binary_tree.cs +++ b/codes/csharp/chapter_tree/array_binary_tree.cs @@ -24,17 +24,17 @@ public int Size() { } /* 获取索引为 i 节点的左子节点的索引 */ - public static int Left(int i) { + public int Left(int i) { return 2 * i + 1; } /* 获取索引为 i 节点的右子节点的索引 */ - public static int Right(int i) { + public int Right(int i) { return 2 * i + 2; } /* 获取索引为 i 节点的父节点的索引 */ - public static int Parent(int i) { + public int Parent(int i) { return (i - 1) / 2; } @@ -108,9 +108,9 @@ public void Test() { // 访问节点 int i = 1; - int l = ArrayBinaryTree.Left(i); - int r = ArrayBinaryTree.Right(i); - int p = ArrayBinaryTree.Parent(i); + int l = abt.Left(i); + int r = abt.Right(i); + int p = abt.Parent(i); Console.WriteLine("\n当前节点的索引为 " + i + " ,值为 " + abt.Val(i)); Console.WriteLine("其左子节点的索引为 " + l + " ,值为 " + (abt.Val(l).HasValue ? abt.Val(l) : "null")); Console.WriteLine("其右子节点的索引为 " + r + " ,值为 " + (abt.Val(r).HasValue ? abt.Val(r) : "null")); diff --git a/docs/chapter_appendix/installation.md b/docs/chapter_appendix/installation.md index 652f33b939..cecfd0ac9f 100644 --- a/docs/chapter_appendix/installation.md +++ b/docs/chapter_appendix/installation.md @@ -35,7 +35,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))。 From 6a73462f0662eb1b3a6b5401210c8ab38af6a4ac Mon Sep 17 00:00:00 2001 From: hpstory <354195783@qq.com> Date: Sat, 25 Nov 2023 23:59:33 +0800 Subject: [PATCH 05/10] remove static --- codes/csharp/.editorconfig | 9 ++++++ .../chapter_array_and_linkedlist/array.cs | 16 +++++----- .../linked_list.cs | 8 ++--- codes/csharp/chapter_backtracking/n_queens.cs | 4 +-- .../chapter_backtracking/permutations_i.cs | 4 +-- .../chapter_backtracking/permutations_ii.cs | 4 +-- .../preorder_traversal_i_compact.cs | 4 +-- .../preorder_traversal_ii_compact.cs | 6 ++-- .../preorder_traversal_iii_compact.cs | 6 ++-- .../preorder_traversal_iii_template.cs | 12 ++++---- .../chapter_backtracking/subset_sum_i.cs | 4 +-- .../subset_sum_i_naive.cs | 4 +-- .../chapter_backtracking/subset_sum_ii.cs | 4 +-- .../iteration.cs | 8 ++--- .../recursion.cs | 8 ++--- .../space_complexity.cs | 14 ++++----- .../time_complexity.cs | 30 +++++++++---------- .../worst_best_time_complexity.cs | 4 +-- .../binary_search_recur.cs | 4 +-- .../chapter_divide_and_conquer/build_tree.cs | 4 +-- .../chapter_divide_and_conquer/hanota.cs | 6 ++-- .../climbing_stairs_backtrack.cs | 4 +-- .../climbing_stairs_constraint_dp.cs | 2 +- .../climbing_stairs_dfs.cs | 4 +-- .../climbing_stairs_dfs_mem.cs | 4 +-- .../climbing_stairs_dp.cs | 4 +-- .../coin_change.cs | 4 +-- .../coin_change_ii.cs | 4 +-- .../edit_distance.cs | 8 ++--- .../chapter_dynamic_programming/knapsack.cs | 8 ++--- .../min_cost_climbing_stairs_dp.cs | 4 +-- .../min_path_sum.cs | 8 ++--- .../unbounded_knapsack.cs | 4 +-- .../chapter_graph/graph_adjacency_list.cs | 21 ++++++------- .../chapter_graph/graph_adjacency_matrix.cs | 6 ++-- codes/csharp/chapter_graph/graph_bfs.cs | 2 +- codes/csharp/chapter_graph/graph_dfs.cs | 4 +-- .../chapter_greedy/coin_change_greedy.cs | 2 +- .../chapter_greedy/fractional_knapsack.cs | 2 +- codes/csharp/chapter_greedy/max_capacity.cs | 2 +- .../chapter_greedy/max_product_cutting.cs | 2 +- .../csharp/chapter_hashing/array_hash_map.cs | 4 +-- .../chapter_hashing/hash_map_chaining.cs | 10 +++---- .../hash_map_open_addressing.cs | 20 ++++++------- codes/csharp/chapter_hashing/simple_hash.cs | 8 ++--- codes/csharp/chapter_heap/heap.cs | 4 +-- codes/csharp/chapter_heap/my_heap.cs | 8 ++--- codes/csharp/chapter_heap/top_k.cs | 2 +- .../csharp/chapter_searching/binary_search.cs | 4 +-- .../chapter_searching/binary_search_edge.cs | 4 +-- .../chapter_searching/hashing_search.cs | 4 +-- .../csharp/chapter_searching/linear_search.cs | 4 +-- codes/csharp/chapter_searching/two_sum.cs | 4 +-- codes/csharp/chapter_sorting/bubble_sort.cs | 4 +-- codes/csharp/chapter_sorting/bucket_sort.cs | 2 +- codes/csharp/chapter_sorting/counting_sort.cs | 4 +-- codes/csharp/chapter_sorting/heap_sort.cs | 4 +-- .../csharp/chapter_sorting/insertion_sort.cs | 2 +- codes/csharp/chapter_sorting/merge_sort.cs | 4 +-- codes/csharp/chapter_sorting/radix_sort.cs | 6 ++-- .../csharp/chapter_sorting/selection_sort.cs | 2 +- .../chapter_stack_and_queue/array_deque.cs | 12 ++++---- .../chapter_stack_and_queue/array_queue.cs | 8 ++--- .../chapter_stack_and_queue/array_stack.cs | 2 +- .../linkedlist_deque.cs | 8 ++--- .../linkedlist_queue.cs | 4 +-- .../linkedlist_stack.cs | 4 +-- .../csharp/chapter_tree/array_binary_tree.cs | 4 +-- codes/csharp/chapter_tree/avl_tree.cs | 16 +++++----- codes/csharp/chapter_tree/binary_tree_bfs.cs | 2 +- codes/csharp/chapter_tree/binary_tree_dfs.cs | 2 +- codes/csharp/utils/TreeNode.cs | 4 +-- 72 files changed, 219 insertions(+), 213 deletions(-) diff --git a/codes/csharp/.editorconfig b/codes/csharp/.editorconfig index 0ade0e81b5..0a2c1df585 100644 --- a/codes/csharp/.editorconfig +++ b/codes/csharp/.editorconfig @@ -26,6 +26,9 @@ dotnet_diagnostic.CS8981.severity = silent # IDE1006: Naming Styles dotnet_diagnostic.IDE1006.severity = silent +# CA1822: Mark members as static +dotnet_diagnostic.CA1822.severity = silent + [*.{cs,vb}] #### Naming styles #### @@ -77,3 +80,9 @@ dotnet_style_operator_placement_when_wrapping = beginning_of_line tab_width = 4 indent_size = 4 end_of_line = crlf + +# IDE0040: Add accessibility modifiers +dotnet_diagnostic.IDE0040.severity = silent + +# IDE0044: Add readonly modifier +dotnet_diagnostic.IDE0044.severity = silent diff --git a/codes/csharp/chapter_array_and_linkedlist/array.cs b/codes/csharp/chapter_array_and_linkedlist/array.cs index fb0ff875b6..5b8fcd38c4 100644 --- a/codes/csharp/chapter_array_and_linkedlist/array.cs +++ b/codes/csharp/chapter_array_and_linkedlist/array.cs @@ -6,7 +6,7 @@ namespace hello_algo.chapter_array_and_linkedlist; public class array { /* 随机访问元素 */ - public static int RandomAccess(int[] nums) { + int RandomAccess(int[] nums) { Random random = new(); // 在区间 [0, nums.Length) 中随机抽取一个数字 int randomIndex = random.Next(nums.Length); @@ -16,7 +16,7 @@ public static int RandomAccess(int[] nums) { } /* 扩展数组长度 */ - public static int[] Extend(int[] nums, int enlarge) { + int[] Extend(int[] nums, int enlarge) { // 初始化一个扩展长度后的数组 int[] res = new int[nums.Length + enlarge]; // 将原数组中的所有元素复制到新数组 @@ -28,7 +28,7 @@ public static int[] Extend(int[] nums, int enlarge) { } /* 在数组的索引 index 处插入元素 num */ - public static void Insert(int[] nums, int num, int index) { + void Insert(int[] nums, int num, int index) { // 把索引 index 以及之后的所有元素向后移动一位 for (int i = nums.Length - 1; i > index; i--) { nums[i] = nums[i - 1]; @@ -38,7 +38,7 @@ public static void Insert(int[] nums, int num, int index) { } /* 删除索引 index 处元素 */ - public static void Remove(int[] nums, int index) { + void Remove(int[] nums, int index) { // 把索引 index 之后的所有元素向前移动一位 for (int i = index; i < nums.Length - 1; i++) { nums[i] = nums[i + 1]; @@ -46,7 +46,7 @@ public static void Remove(int[] nums, int index) { } /* 遍历数组 */ - public static void Traverse(int[] nums) { + void Traverse(int[] nums) { int count = 0; // 通过索引遍历数组 for (int i = 0; i < nums.Length; i++) { @@ -59,7 +59,7 @@ public static void Traverse(int[] nums) { } /* 在数组中查找指定元素 */ - public static int Find(int[] nums, int target) { + int Find(int[] nums, int target) { for (int i = 0; i < nums.Length; i++) { if (nums[i] == target) return i; @@ -68,13 +68,13 @@ public static int Find(int[] nums, int target) { } /* 辅助函数,数组转字符串 */ - public static string ToString(int[] nums) { + string ToString(int[] nums) { return string.Join(",", nums); } [Test] - public static void Test() { + public void Test() { // 初始化数组 int[] arr = new int[5]; Console.WriteLine("数组 arr = " + ToString(arr)); diff --git a/codes/csharp/chapter_array_and_linkedlist/linked_list.cs b/codes/csharp/chapter_array_and_linkedlist/linked_list.cs index 9cdfca68bd..2da7bd8720 100644 --- a/codes/csharp/chapter_array_and_linkedlist/linked_list.cs +++ b/codes/csharp/chapter_array_and_linkedlist/linked_list.cs @@ -6,14 +6,14 @@ namespace hello_algo.chapter_array_and_linkedlist; public class linked_list { /* 在链表的节点 n0 之后插入节点 P */ - public static void Insert(ListNode n0, ListNode P) { + void Insert(ListNode n0, ListNode P) { ListNode? n1 = n0.next; P.next = n1; n0.next = P; } /* 删除链表的节点 n0 之后的首个节点 */ - public static void Remove(ListNode n0) { + void Remove(ListNode n0) { if (n0.next == null) return; // n0 -> P -> n1 @@ -23,7 +23,7 @@ public static void Remove(ListNode n0) { } /* 访问链表中索引为 index 的节点 */ - public static ListNode? Access(ListNode? head, int index) { + ListNode? Access(ListNode? head, int index) { for (int i = 0; i < index; i++) { if (head == null) return null; @@ -33,7 +33,7 @@ public static void Remove(ListNode n0) { } /* 在链表中查找值为 target 的首个节点 */ - public static int Find(ListNode? head, int target) { + int Find(ListNode? head, int target) { int index = 0; while (head != null) { if (head.val == target) diff --git a/codes/csharp/chapter_backtracking/n_queens.cs b/codes/csharp/chapter_backtracking/n_queens.cs index d19355de73..84fa22c610 100644 --- a/codes/csharp/chapter_backtracking/n_queens.cs +++ b/codes/csharp/chapter_backtracking/n_queens.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_backtracking; public class n_queens { /* 回溯算法:N 皇后 */ - static void Backtrack(int row, int n, List> state, List>> res, + void Backtrack(int row, int n, List> state, List>> res, bool[] cols, bool[] diags1, bool[] diags2) { // 当放置完所有行时,记录解 if (row == n) { @@ -39,7 +39,7 @@ static void Backtrack(int row, int n, List> state, List>> NQueens(int n) { + List>> NQueens(int n) { // 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位 List> state = []; for (int i = 0; i < n; i++) { diff --git a/codes/csharp/chapter_backtracking/permutations_i.cs b/codes/csharp/chapter_backtracking/permutations_i.cs index f294296eae..8096973731 100644 --- a/codes/csharp/chapter_backtracking/permutations_i.cs +++ b/codes/csharp/chapter_backtracking/permutations_i.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_backtracking; public class permutations_i { /* 回溯算法:全排列 I */ - static void Backtrack(List state, int[] choices, bool[] selected, List> res) { + void Backtrack(List state, int[] choices, bool[] selected, List> res) { // 当状态长度等于元素数量时,记录解 if (state.Count == choices.Length) { res.Add(new List(state)); @@ -32,7 +32,7 @@ static void Backtrack(List state, int[] choices, bool[] selected, List> PermutationsI(int[] nums) { + List> PermutationsI(int[] nums) { List> res = []; Backtrack([], nums, new bool[nums.Length], res); return res; diff --git a/codes/csharp/chapter_backtracking/permutations_ii.cs b/codes/csharp/chapter_backtracking/permutations_ii.cs index 08233d01c1..68bda7c203 100644 --- a/codes/csharp/chapter_backtracking/permutations_ii.cs +++ b/codes/csharp/chapter_backtracking/permutations_ii.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_backtracking; public class permutations_ii { /* 回溯算法:全排列 II */ - static void Backtrack(List state, int[] choices, bool[] selected, List> res) { + void Backtrack(List state, int[] choices, bool[] selected, List> res) { // 当状态长度等于元素数量时,记录解 if (state.Count == choices.Length) { res.Add(new List(state)); @@ -34,7 +34,7 @@ static void Backtrack(List state, int[] choices, bool[] selected, List> PermutationsII(int[] nums) { + List> PermutationsII(int[] nums) { List> res = []; Backtrack([], nums, new bool[nums.Length], res); return res; diff --git a/codes/csharp/chapter_backtracking/preorder_traversal_i_compact.cs b/codes/csharp/chapter_backtracking/preorder_traversal_i_compact.cs index bbc0171df4..58e46e8042 100644 --- a/codes/csharp/chapter_backtracking/preorder_traversal_i_compact.cs +++ b/codes/csharp/chapter_backtracking/preorder_traversal_i_compact.cs @@ -7,10 +7,10 @@ namespace hello_algo.chapter_backtracking; public class preorder_traversal_i_compact { - static readonly List res = []; + List res = []; /* 前序遍历:例题一 */ - static void PreOrder(TreeNode? root) { + void PreOrder(TreeNode? root) { if (root == null) { return; } diff --git a/codes/csharp/chapter_backtracking/preorder_traversal_ii_compact.cs b/codes/csharp/chapter_backtracking/preorder_traversal_ii_compact.cs index 7089465870..1bd8e686c0 100644 --- a/codes/csharp/chapter_backtracking/preorder_traversal_ii_compact.cs +++ b/codes/csharp/chapter_backtracking/preorder_traversal_ii_compact.cs @@ -7,11 +7,11 @@ namespace hello_algo.chapter_backtracking; public class preorder_traversal_ii_compact { - static readonly List path = []; - static readonly List> res = []; + List path = []; + List> res = []; /* 前序遍历:例题二 */ - static void PreOrder(TreeNode? root) { + void PreOrder(TreeNode? root) { if (root == null) { return; } diff --git a/codes/csharp/chapter_backtracking/preorder_traversal_iii_compact.cs b/codes/csharp/chapter_backtracking/preorder_traversal_iii_compact.cs index 9cf32bd231..ac60b792ca 100644 --- a/codes/csharp/chapter_backtracking/preorder_traversal_iii_compact.cs +++ b/codes/csharp/chapter_backtracking/preorder_traversal_iii_compact.cs @@ -7,11 +7,11 @@ namespace hello_algo.chapter_backtracking; public class preorder_traversal_iii_compact { - static readonly List path = []; - static readonly List> res = []; + List path = []; + List> res = []; /* 前序遍历:例题三 */ - static void PreOrder(TreeNode? root) { + void PreOrder(TreeNode? root) { // 剪枝 if (root == null || root.val == 3) { return; diff --git a/codes/csharp/chapter_backtracking/preorder_traversal_iii_template.cs b/codes/csharp/chapter_backtracking/preorder_traversal_iii_template.cs index 6fda6d8f88..be4b2b1ea0 100644 --- a/codes/csharp/chapter_backtracking/preorder_traversal_iii_template.cs +++ b/codes/csharp/chapter_backtracking/preorder_traversal_iii_template.cs @@ -8,32 +8,32 @@ namespace hello_algo.chapter_backtracking; public class preorder_traversal_iii_template { /* 判断当前状态是否为解 */ - static bool IsSolution(List state) { + bool IsSolution(List state) { return state.Count != 0 && state[^1].val == 7; } /* 记录解 */ - static void RecordSolution(List state, List> res) { + void RecordSolution(List state, List> res) { res.Add(new List(state)); } /* 判断在当前状态下,该选择是否合法 */ - static bool IsValid(List state, TreeNode choice) { + bool IsValid(List state, TreeNode choice) { return choice != null && choice.val != 3; } /* 更新状态 */ - static void MakeChoice(List state, TreeNode choice) { + void MakeChoice(List state, TreeNode choice) { state.Add(choice); } /* 恢复状态 */ - static void UndoChoice(List state, TreeNode choice) { + void UndoChoice(List state, TreeNode choice) { state.RemoveAt(state.Count - 1); } /* 回溯算法:例题三 */ - static void Backtrack(List state, List choices, List> res) { + void Backtrack(List state, List choices, List> res) { // 检查是否为解 if (IsSolution(state)) { // 记录解 diff --git a/codes/csharp/chapter_backtracking/subset_sum_i.cs b/codes/csharp/chapter_backtracking/subset_sum_i.cs index 0cf9d025b2..fe81e32048 100644 --- a/codes/csharp/chapter_backtracking/subset_sum_i.cs +++ b/codes/csharp/chapter_backtracking/subset_sum_i.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_backtracking; public class subset_sum_i { /* 回溯算法:子集和 I */ - public static void Backtrack(List state, int target, int[] choices, int start, List> res) { + void Backtrack(List state, int target, int[] choices, int start, List> res) { // 子集和等于 target 时,记录解 if (target == 0) { res.Add(new List(state)); @@ -32,7 +32,7 @@ public static void Backtrack(List state, int target, int[] choices, int sta } /* 求解子集和 I */ - public static List> SubsetSumI(int[] nums, int target) { + List> SubsetSumI(int[] nums, int target) { List state = []; // 状态(子集) Array.Sort(nums); // 对 nums 进行排序 int start = 0; // 遍历起始点 diff --git a/codes/csharp/chapter_backtracking/subset_sum_i_naive.cs b/codes/csharp/chapter_backtracking/subset_sum_i_naive.cs index aebbdf3134..54c8a02e23 100644 --- a/codes/csharp/chapter_backtracking/subset_sum_i_naive.cs +++ b/codes/csharp/chapter_backtracking/subset_sum_i_naive.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_backtracking; public class subset_sum_i_naive { /* 回溯算法:子集和 I */ - public static void Backtrack(List state, int target, int total, int[] choices, List> res) { + void Backtrack(List state, int target, int total, int[] choices, List> res) { // 子集和等于 target 时,记录解 if (total == target) { res.Add(new List(state)); @@ -30,7 +30,7 @@ public static void Backtrack(List state, int target, int total, int[] choic } /* 求解子集和 I(包含重复子集) */ - public static List> SubsetSumINaive(int[] nums, int target) { + List> SubsetSumINaive(int[] nums, int target) { List state = []; // 状态(子集) int total = 0; // 子集和 List> res = []; // 结果列表(子集列表) diff --git a/codes/csharp/chapter_backtracking/subset_sum_ii.cs b/codes/csharp/chapter_backtracking/subset_sum_ii.cs index 1e22589dcf..a3daf0cd21 100644 --- a/codes/csharp/chapter_backtracking/subset_sum_ii.cs +++ b/codes/csharp/chapter_backtracking/subset_sum_ii.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_backtracking; public class subset_sum_ii { /* 回溯算法:子集和 II */ - public static void Backtrack(List state, int target, int[] choices, int start, List> res) { + void Backtrack(List state, int target, int[] choices, int start, List> res) { // 子集和等于 target 时,记录解 if (target == 0) { res.Add(new List(state)); @@ -37,7 +37,7 @@ public static void Backtrack(List state, int target, int[] choices, int sta } /* 求解子集和 II */ - public static List> SubsetSumII(int[] nums, int target) { + List> SubsetSumII(int[] nums, int target) { List state = []; // 状态(子集) Array.Sort(nums); // 对 nums 进行排序 int start = 0; // 遍历起始点 diff --git a/codes/csharp/chapter_computational_complexity/iteration.cs b/codes/csharp/chapter_computational_complexity/iteration.cs index f8381bbe91..38ae18cef3 100644 --- a/codes/csharp/chapter_computational_complexity/iteration.cs +++ b/codes/csharp/chapter_computational_complexity/iteration.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_computational_complexity; public class iteration { /* for 循环 */ - public static int ForLoop(int n) { + int ForLoop(int n) { int res = 0; // 循环求和 1, 2, ..., n-1, n for (int i = 1; i <= n; i++) { @@ -18,7 +18,7 @@ public static int ForLoop(int n) { } /* while 循环 */ - public static int WhileLoop(int n) { + int WhileLoop(int n) { int res = 0; int i = 1; // 初始化条件变量 // 循环求和 1, 2, ..., n-1, n @@ -30,7 +30,7 @@ public static int WhileLoop(int n) { } /* while 循环(两次更新) */ - public static int WhileLoopII(int n) { + int WhileLoopII(int n) { int res = 0; int i = 1; // 初始化条件变量 // 循环求和 1, 2, 4, 5... @@ -44,7 +44,7 @@ public static int WhileLoopII(int n) { } /* 双层 for 循环 */ - public static string NestedForLoop(int n) { + string NestedForLoop(int n) { StringBuilder res = new(); // 循环 i = 1, 2, ..., n-1, n for (int i = 1; i <= n; i++) { diff --git a/codes/csharp/chapter_computational_complexity/recursion.cs b/codes/csharp/chapter_computational_complexity/recursion.cs index 475641de83..c0638b9cc2 100644 --- a/codes/csharp/chapter_computational_complexity/recursion.cs +++ b/codes/csharp/chapter_computational_complexity/recursion.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_computational_complexity; public class recursion { /* 递归 */ - public static int Recur(int n) { + int Recur(int n) { // 终止条件 if (n == 1) return 1; @@ -19,7 +19,7 @@ public static int Recur(int n) { } /* 使用迭代模拟递归 */ - public static int ForLoopRecur(int n) { + int ForLoopRecur(int n) { // 使用一个显式的栈来模拟系统调用栈 Stack stack = new(); int res = 0; @@ -38,7 +38,7 @@ public static int ForLoopRecur(int n) { } /* 尾递归 */ - public static int TailRecur(int n, int res) { + int TailRecur(int n, int res) { // 终止条件 if (n == 0) return res; @@ -47,7 +47,7 @@ public static int TailRecur(int n, int res) { } /* 斐波那契数列:递归 */ - public static int Fib(int n) { + int Fib(int n) { // 终止条件 f(1) = 0, f(2) = 1 if (n == 1 || n == 2) return n - 1; diff --git a/codes/csharp/chapter_computational_complexity/space_complexity.cs b/codes/csharp/chapter_computational_complexity/space_complexity.cs index c763f58f9f..44645cc2d0 100644 --- a/codes/csharp/chapter_computational_complexity/space_complexity.cs +++ b/codes/csharp/chapter_computational_complexity/space_complexity.cs @@ -8,13 +8,13 @@ namespace hello_algo.chapter_computational_complexity; public class space_complexity { /* 函数 */ - static int Function() { + int Function() { // 执行某些操作 return 0; } /* 常数阶 */ - static void Constant(int n) { + void Constant(int n) { // 常量、变量、对象占用 O(1) 空间 int a = 0; int b = 0; @@ -31,7 +31,7 @@ static void Constant(int n) { } /* 线性阶 */ - static void Linear(int n) { + void Linear(int n) { // 长度为 n 的数组占用 O(n) 空间 int[] nums = new int[n]; // 长度为 n 的列表占用 O(n) 空间 @@ -47,14 +47,14 @@ static void Linear(int n) { } /* 线性阶(递归实现) */ - static void LinearRecur(int n) { + void LinearRecur(int n) { Console.WriteLine("递归 n = " + n); if (n == 1) return; LinearRecur(n - 1); } /* 平方阶 */ - static void Quadratic(int n) { + void Quadratic(int n) { // 矩阵占用 O(n^2) 空间 int[,] numMatrix = new int[n, n]; // 二维列表占用 O(n^2) 空间 @@ -69,7 +69,7 @@ static void Quadratic(int n) { } /* 平方阶(递归实现) */ - static int QuadraticRecur(int n) { + int QuadraticRecur(int n) { if (n <= 0) return 0; int[] nums = new int[n]; Console.WriteLine("递归 n = " + n + " 中的 nums 长度 = " + nums.Length); @@ -77,7 +77,7 @@ static int QuadraticRecur(int n) { } /* 指数阶(建立满二叉树) */ - static TreeNode? BuildTree(int n) { + TreeNode? BuildTree(int n) { if (n == 0) return null; TreeNode root = new(0) { left = BuildTree(n - 1), diff --git a/codes/csharp/chapter_computational_complexity/time_complexity.cs b/codes/csharp/chapter_computational_complexity/time_complexity.cs index e206f0c79a..722b768ba0 100644 --- a/codes/csharp/chapter_computational_complexity/time_complexity.cs +++ b/codes/csharp/chapter_computational_complexity/time_complexity.cs @@ -7,7 +7,7 @@ namespace hello_algo.chapter_computational_complexity; public class time_complexity { - public static void Algorithm(int n) { + void Algorithm(int n) { int a = 1; // +0(技巧 1) a += n; // +0(技巧 1) // +n(技巧 2) @@ -23,26 +23,26 @@ public static void Algorithm(int n) { } // 算法 A 时间复杂度:常数阶 - public static void AlgorithmA(int n) { + void AlgorithmA(int n) { Console.WriteLine(0); } // 算法 B 时间复杂度:线性阶 - public static void AlgorithmB(int n) { + void AlgorithmB(int n) { for (int i = 0; i < n; i++) { Console.WriteLine(0); } } // 算法 C 时间复杂度:常数阶 - public static void AlgorithmC(int n) { + void AlgorithmC(int n) { for (int i = 0; i < 1000000; i++) { Console.WriteLine(0); } } /* 常数阶 */ - static int Constant(int n) { + int Constant(int n) { int count = 0; int size = 100000; for (int i = 0; i < size; i++) @@ -51,7 +51,7 @@ static int Constant(int n) { } /* 线性阶 */ - static int Linear(int n) { + int Linear(int n) { int count = 0; for (int i = 0; i < n; i++) count++; @@ -59,7 +59,7 @@ static int Linear(int n) { } /* 线性阶(遍历数组) */ - static int ArrayTraversal(int[] nums) { + int ArrayTraversal(int[] nums) { int count = 0; // 循环次数与数组长度成正比 foreach (int num in nums) { @@ -69,7 +69,7 @@ static int ArrayTraversal(int[] nums) { } /* 平方阶 */ - static int Quadratic(int n) { + int Quadratic(int n) { int count = 0; // 循环次数与数组长度成平方关系 for (int i = 0; i < n; i++) { @@ -81,7 +81,7 @@ static int Quadratic(int n) { } /* 平方阶(冒泡排序) */ - static int BubbleSort(int[] nums) { + int BubbleSort(int[] nums) { int count = 0; // 计数器 // 外循环:未排序区间为 [0, i] for (int i = nums.Length - 1; i > 0; i--) { @@ -98,7 +98,7 @@ static int BubbleSort(int[] nums) { } /* 指数阶(循环实现) */ - static int Exponential(int n) { + int Exponential(int n) { int count = 0, bas = 1; // 细胞每轮一分为二,形成数列 1, 2, 4, 8, ..., 2^(n-1) for (int i = 0; i < n; i++) { @@ -112,13 +112,13 @@ static int Exponential(int n) { } /* 指数阶(递归实现) */ - static int ExpRecur(int n) { + int ExpRecur(int n) { if (n == 1) return 1; return ExpRecur(n - 1) + ExpRecur(n - 1) + 1; } /* 对数阶(循环实现) */ - static int Logarithmic(float n) { + int Logarithmic(float n) { int count = 0; while (n > 1) { n /= 2; @@ -128,13 +128,13 @@ static int Logarithmic(float n) { } /* 对数阶(递归实现) */ - static int LogRecur(float n) { + int LogRecur(float n) { if (n <= 1) return 0; return LogRecur(n / 2) + 1; } /* 线性对数阶 */ - static int LinearLogRecur(float n) { + int LinearLogRecur(float n) { if (n <= 1) return 1; int count = LinearLogRecur(n / 2) + LinearLogRecur(n / 2); for (int i = 0; i < n; i++) { @@ -144,7 +144,7 @@ static int LinearLogRecur(float n) { } /* 阶乘阶(递归实现) */ - static int FactorialRecur(int n) { + int FactorialRecur(int n) { if (n == 0) return 1; int count = 0; // 从 1 个分裂出 n 个 diff --git a/codes/csharp/chapter_computational_complexity/worst_best_time_complexity.cs b/codes/csharp/chapter_computational_complexity/worst_best_time_complexity.cs index bdf86ce1b9..c6770718b8 100644 --- a/codes/csharp/chapter_computational_complexity/worst_best_time_complexity.cs +++ b/codes/csharp/chapter_computational_complexity/worst_best_time_complexity.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_computational_complexity; public class worst_best_time_complexity { /* 生成一个数组,元素为 { 1, 2, ..., n },顺序被打乱 */ - static int[] RandomNumbers(int n) { + int[] RandomNumbers(int n) { int[] nums = new int[n]; // 生成数组 nums = { 1, 2, 3, ..., n } for (int i = 0; i < n; i++) { @@ -24,7 +24,7 @@ static int[] RandomNumbers(int n) { } /* 查找数组 nums 中数字 1 所在索引 */ - static int FindOne(int[] nums) { + int FindOne(int[] nums) { for (int i = 0; i < nums.Length; i++) { // 当元素 1 在数组头部时,达到最佳时间复杂度 O(1) // 当元素 1 在数组尾部时,达到最差时间复杂度 O(n) diff --git a/codes/csharp/chapter_divide_and_conquer/binary_search_recur.cs b/codes/csharp/chapter_divide_and_conquer/binary_search_recur.cs index 2a15c1de49..5e604aa38e 100644 --- a/codes/csharp/chapter_divide_and_conquer/binary_search_recur.cs +++ b/codes/csharp/chapter_divide_and_conquer/binary_search_recur.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_divide_and_conquer; public class binary_search_recur { /* 二分查找:问题 f(i, j) */ - public static int DFS(int[] nums, int target, int i, int j) { + int DFS(int[] nums, int target, int i, int j) { // 若区间为空,代表无目标元素,则返回 -1 if (i > j) { return -1; @@ -28,7 +28,7 @@ public static int DFS(int[] nums, int target, int i, int j) { } /* 二分查找 */ - public static int BinarySearch(int[] nums, int target) { + int BinarySearch(int[] nums, int target) { int n = nums.Length; // 求解问题 f(0, n-1) return DFS(nums, target, 0, n - 1); diff --git a/codes/csharp/chapter_divide_and_conquer/build_tree.cs b/codes/csharp/chapter_divide_and_conquer/build_tree.cs index 89d9e5a3fa..c85c90f47c 100644 --- a/codes/csharp/chapter_divide_and_conquer/build_tree.cs +++ b/codes/csharp/chapter_divide_and_conquer/build_tree.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_divide_and_conquer; public class build_tree { /* 构建二叉树:分治 */ - public static TreeNode? DFS(int[] preorder, Dictionary inorderMap, int i, int l, int r) { + TreeNode? DFS(int[] preorder, Dictionary inorderMap, int i, int l, int r) { // 子树区间为空时终止 if (r - l < 0) return null; @@ -25,7 +25,7 @@ public class build_tree { } /* 构建二叉树 */ - public static TreeNode? BuildTree(int[] preorder, int[] inorder) { + TreeNode? BuildTree(int[] preorder, int[] inorder) { // 初始化哈希表,存储 inorder 元素到索引的映射 Dictionary inorderMap = []; for (int i = 0; i < inorder.Length; i++) { diff --git a/codes/csharp/chapter_divide_and_conquer/hanota.cs b/codes/csharp/chapter_divide_and_conquer/hanota.cs index d1007b9c3c..c112fbeaa1 100644 --- a/codes/csharp/chapter_divide_and_conquer/hanota.cs +++ b/codes/csharp/chapter_divide_and_conquer/hanota.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_divide_and_conquer; public class hanota { /* 移动一个圆盘 */ - public static void Move(List src, List tar) { + void Move(List src, List tar) { // 从 src 顶部拿出一个圆盘 int pan = src[^1]; src.RemoveAt(src.Count - 1); @@ -17,7 +17,7 @@ public static void Move(List src, List tar) { } /* 求解汉诺塔:问题 f(i) */ - public static void DFS(int i, List src, List buf, List tar) { + void DFS(int i, List src, List buf, List tar) { // 若 src 只剩下一个圆盘,则直接将其移到 tar if (i == 1) { Move(src, tar); @@ -32,7 +32,7 @@ public static void DFS(int i, List src, List buf, List tar) { } /* 求解汉诺塔 */ - public static void SolveHanota(List A, List B, List C) { + void SolveHanota(List A, List B, List C) { int n = A.Count; // 将 A 顶部 n 个圆盘借助 B 移到 C DFS(n, A, B, C); diff --git a/codes/csharp/chapter_dynamic_programming/climbing_stairs_backtrack.cs b/codes/csharp/chapter_dynamic_programming/climbing_stairs_backtrack.cs index 93a0fed868..d7ee0baa5e 100644 --- a/codes/csharp/chapter_dynamic_programming/climbing_stairs_backtrack.cs +++ b/codes/csharp/chapter_dynamic_programming/climbing_stairs_backtrack.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_dynamic_programming; public class climbing_stairs_backtrack { /* 回溯 */ - public static void Backtrack(List choices, int state, int n, List res) { + void Backtrack(List choices, int state, int n, List res) { // 当爬到第 n 阶时,方案数量加 1 if (state == n) res[0]++; @@ -24,7 +24,7 @@ public static void Backtrack(List choices, int state, int n, List res) } /* 爬楼梯:回溯 */ - public int ClimbingStairsBacktrack(int n) { + int ClimbingStairsBacktrack(int n) { List choices = [1, 2]; // 可选择向上爬 1 或 2 阶 int state = 0; // 从第 0 阶开始爬 List res = [0]; // 使用 res[0] 记录方案数量 diff --git a/codes/csharp/chapter_dynamic_programming/climbing_stairs_constraint_dp.cs b/codes/csharp/chapter_dynamic_programming/climbing_stairs_constraint_dp.cs index 16be10ec2f..a972e442ee 100644 --- a/codes/csharp/chapter_dynamic_programming/climbing_stairs_constraint_dp.cs +++ b/codes/csharp/chapter_dynamic_programming/climbing_stairs_constraint_dp.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_dynamic_programming; public class climbing_stairs_constraint_dp { /* 带约束爬楼梯:动态规划 */ - public static int ClimbingStairsConstraintDP(int n) { + int ClimbingStairsConstraintDP(int n) { if (n == 1 || n == 2) { return 1; } diff --git a/codes/csharp/chapter_dynamic_programming/climbing_stairs_dfs.cs b/codes/csharp/chapter_dynamic_programming/climbing_stairs_dfs.cs index 8839e00f94..868532ac2a 100644 --- a/codes/csharp/chapter_dynamic_programming/climbing_stairs_dfs.cs +++ b/codes/csharp/chapter_dynamic_programming/climbing_stairs_dfs.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_dynamic_programming; public class climbing_stairs_dfs { /* 搜索 */ - public static int DFS(int i) { + int DFS(int i) { // 已知 dp[1] 和 dp[2] ,返回之 if (i == 1 || i == 2) return i; @@ -18,7 +18,7 @@ public static int DFS(int i) { } /* 爬楼梯:搜索 */ - public static int ClimbingStairsDFS(int n) { + int ClimbingStairsDFS(int n) { return DFS(n); } diff --git a/codes/csharp/chapter_dynamic_programming/climbing_stairs_dfs_mem.cs b/codes/csharp/chapter_dynamic_programming/climbing_stairs_dfs_mem.cs index 596db264a7..8bb40a675e 100644 --- a/codes/csharp/chapter_dynamic_programming/climbing_stairs_dfs_mem.cs +++ b/codes/csharp/chapter_dynamic_programming/climbing_stairs_dfs_mem.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_dynamic_programming; public class climbing_stairs_dfs_mem { /* 记忆化搜索 */ - public static int DFS(int i, int[] mem) { + int DFS(int i, int[] mem) { // 已知 dp[1] 和 dp[2] ,返回之 if (i == 1 || i == 2) return i; @@ -23,7 +23,7 @@ public static int DFS(int i, int[] mem) { } /* 爬楼梯:记忆化搜索 */ - public static int ClimbingStairsDFSMem(int n) { + int ClimbingStairsDFSMem(int n) { // mem[i] 记录爬到第 i 阶的方案总数,-1 代表无记录 int[] mem = new int[n + 1]; Array.Fill(mem, -1); diff --git a/codes/csharp/chapter_dynamic_programming/climbing_stairs_dp.cs b/codes/csharp/chapter_dynamic_programming/climbing_stairs_dp.cs index 5794f83acb..8bcb2e6376 100644 --- a/codes/csharp/chapter_dynamic_programming/climbing_stairs_dp.cs +++ b/codes/csharp/chapter_dynamic_programming/climbing_stairs_dp.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_dynamic_programming; public class climbing_stairs_dp { /* 爬楼梯:动态规划 */ - public static int ClimbingStairsDP(int n) { + int ClimbingStairsDP(int n) { if (n == 1 || n == 2) return n; // 初始化 dp 表,用于存储子问题的解 @@ -24,7 +24,7 @@ public static int ClimbingStairsDP(int n) { } /* 爬楼梯:空间优化后的动态规划 */ - public static int ClimbingStairsDPComp(int n) { + int ClimbingStairsDPComp(int n) { if (n == 1 || n == 2) return n; int a = 1, b = 2; diff --git a/codes/csharp/chapter_dynamic_programming/coin_change.cs b/codes/csharp/chapter_dynamic_programming/coin_change.cs index 0187bbd8fd..43b32aef90 100644 --- a/codes/csharp/chapter_dynamic_programming/coin_change.cs +++ b/codes/csharp/chapter_dynamic_programming/coin_change.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_dynamic_programming; public class coin_change { /* 零钱兑换:动态规划 */ - public static int CoinChangeDP(int[] coins, int amt) { + int CoinChangeDP(int[] coins, int amt) { int n = coins.Length; int MAX = amt + 1; // 初始化 dp 表 @@ -33,7 +33,7 @@ public static int CoinChangeDP(int[] coins, int amt) { } /* 零钱兑换:空间优化后的动态规划 */ - public static int CoinChangeDPComp(int[] coins, int amt) { + int CoinChangeDPComp(int[] coins, int amt) { int n = coins.Length; int MAX = amt + 1; // 初始化 dp 表 diff --git a/codes/csharp/chapter_dynamic_programming/coin_change_ii.cs b/codes/csharp/chapter_dynamic_programming/coin_change_ii.cs index 3d8946ca6e..0b53b2015c 100644 --- a/codes/csharp/chapter_dynamic_programming/coin_change_ii.cs +++ b/codes/csharp/chapter_dynamic_programming/coin_change_ii.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_dynamic_programming; public class coin_change_ii { /* 零钱兑换 II:动态规划 */ - public static int CoinChangeIIDP(int[] coins, int amt) { + int CoinChangeIIDP(int[] coins, int amt) { int n = coins.Length; // 初始化 dp 表 int[,] dp = new int[n + 1, amt + 1]; @@ -32,7 +32,7 @@ public static int CoinChangeIIDP(int[] coins, int amt) { } /* 零钱兑换 II:空间优化后的动态规划 */ - public static int CoinChangeIIDPComp(int[] coins, int amt) { + int CoinChangeIIDPComp(int[] coins, int amt) { int n = coins.Length; // 初始化 dp 表 int[] dp = new int[amt + 1]; diff --git a/codes/csharp/chapter_dynamic_programming/edit_distance.cs b/codes/csharp/chapter_dynamic_programming/edit_distance.cs index 58b076710a..e7835343f4 100644 --- a/codes/csharp/chapter_dynamic_programming/edit_distance.cs +++ b/codes/csharp/chapter_dynamic_programming/edit_distance.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_dynamic_programming; public class edit_distance { /* 编辑距离:暴力搜索 */ - public static int EditDistanceDFS(string s, string t, int i, int j) { + int EditDistanceDFS(string s, string t, int i, int j) { // 若 s 和 t 都为空,则返回 0 if (i == 0 && j == 0) return 0; @@ -30,7 +30,7 @@ public static int EditDistanceDFS(string s, string t, int i, int j) { } /* 编辑距离:记忆化搜索 */ - public static int EditDistanceDFSMem(string s, string t, int[][] mem, int i, int j) { + int EditDistanceDFSMem(string s, string t, int[][] mem, int i, int j) { // 若 s 和 t 都为空,则返回 0 if (i == 0 && j == 0) return 0; @@ -56,7 +56,7 @@ public static int EditDistanceDFSMem(string s, string t, int[][] mem, int i, int } /* 编辑距离:动态规划 */ - public static int EditDistanceDP(string s, string t) { + int EditDistanceDP(string s, string t) { int n = s.Length, m = t.Length; int[,] dp = new int[n + 1, m + 1]; // 状态转移:首行首列 @@ -82,7 +82,7 @@ public static int EditDistanceDP(string s, string t) { } /* 编辑距离:空间优化后的动态规划 */ - public static int EditDistanceDPComp(string s, string t) { + int EditDistanceDPComp(string s, string t) { int n = s.Length, m = t.Length; int[] dp = new int[m + 1]; // 状态转移:首行 diff --git a/codes/csharp/chapter_dynamic_programming/knapsack.cs b/codes/csharp/chapter_dynamic_programming/knapsack.cs index 545ee8a161..b786578565 100644 --- a/codes/csharp/chapter_dynamic_programming/knapsack.cs +++ b/codes/csharp/chapter_dynamic_programming/knapsack.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_dynamic_programming; public class knapsack { /* 0-1 背包:暴力搜索 */ - public static int KnapsackDFS(int[] weight, int[] val, int i, int c) { + int KnapsackDFS(int[] weight, int[] val, int i, int c) { // 若已选完所有物品或背包无容量,则返回价值 0 if (i == 0 || c == 0) { return 0; @@ -25,7 +25,7 @@ public static int KnapsackDFS(int[] weight, int[] val, int i, int c) { } /* 0-1 背包:记忆化搜索 */ - public static int KnapsackDFSMem(int[] weight, int[] val, int[][] mem, int i, int c) { + int KnapsackDFSMem(int[] weight, int[] val, int[][] mem, int i, int c) { // 若已选完所有物品或背包无容量,则返回价值 0 if (i == 0 || c == 0) { return 0; @@ -47,7 +47,7 @@ public static int KnapsackDFSMem(int[] weight, int[] val, int[][] mem, int i, in } /* 0-1 背包:动态规划 */ - public static int KnapsackDP(int[] weight, int[] val, int cap) { + int KnapsackDP(int[] weight, int[] val, int cap) { int n = weight.Length; // 初始化 dp 表 int[,] dp = new int[n + 1, cap + 1]; @@ -67,7 +67,7 @@ public static int KnapsackDP(int[] weight, int[] val, int cap) { } /* 0-1 背包:空间优化后的动态规划 */ - public static int KnapsackDPComp(int[] weight, int[] val, int cap) { + int KnapsackDPComp(int[] weight, int[] val, int cap) { int n = weight.Length; // 初始化 dp 表 int[] dp = new int[cap + 1]; diff --git a/codes/csharp/chapter_dynamic_programming/min_cost_climbing_stairs_dp.cs b/codes/csharp/chapter_dynamic_programming/min_cost_climbing_stairs_dp.cs index 5992540c89..f54d9a8afc 100644 --- a/codes/csharp/chapter_dynamic_programming/min_cost_climbing_stairs_dp.cs +++ b/codes/csharp/chapter_dynamic_programming/min_cost_climbing_stairs_dp.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_dynamic_programming; public class min_cost_climbing_stairs_dp { /* 爬楼梯最小代价:动态规划 */ - public static int MinCostClimbingStairsDP(int[] cost) { + int MinCostClimbingStairsDP(int[] cost) { int n = cost.Length - 1; if (n == 1 || n == 2) return cost[n]; @@ -25,7 +25,7 @@ public static int MinCostClimbingStairsDP(int[] cost) { } /* 爬楼梯最小代价:空间优化后的动态规划 */ - public static int MinCostClimbingStairsDPComp(int[] cost) { + int MinCostClimbingStairsDPComp(int[] cost) { int n = cost.Length - 1; if (n == 1 || n == 2) return cost[n]; diff --git a/codes/csharp/chapter_dynamic_programming/min_path_sum.cs b/codes/csharp/chapter_dynamic_programming/min_path_sum.cs index 72f2f10bc7..dd95b91b8f 100644 --- a/codes/csharp/chapter_dynamic_programming/min_path_sum.cs +++ b/codes/csharp/chapter_dynamic_programming/min_path_sum.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_dynamic_programming; public class min_path_sum { /* 最小路径和:暴力搜索 */ - public static int MinPathSumDFS(int[][] grid, int i, int j) { + int MinPathSumDFS(int[][] grid, int i, int j) { // 若为左上角单元格,则终止搜索 if (i == 0 && j == 0) { return grid[0][0]; @@ -25,7 +25,7 @@ public static int MinPathSumDFS(int[][] grid, int i, int j) { } /* 最小路径和:记忆化搜索 */ - public static int MinPathSumDFSMem(int[][] grid, int[][] mem, int i, int j) { + int MinPathSumDFSMem(int[][] grid, int[][] mem, int i, int j) { // 若为左上角单元格,则终止搜索 if (i == 0 && j == 0) { return grid[0][0]; @@ -47,7 +47,7 @@ public static int MinPathSumDFSMem(int[][] grid, int[][] mem, int i, int j) { } /* 最小路径和:动态规划 */ - public static int MinPathSumDP(int[][] grid) { + int MinPathSumDP(int[][] grid) { int n = grid.Length, m = grid[0].Length; // 初始化 dp 表 int[,] dp = new int[n, m]; @@ -70,7 +70,7 @@ public static int MinPathSumDP(int[][] grid) { } /* 最小路径和:空间优化后的动态规划 */ - public static int MinPathSumDPComp(int[][] grid) { + int MinPathSumDPComp(int[][] grid) { int n = grid.Length, m = grid[0].Length; // 初始化 dp 表 int[] dp = new int[m]; diff --git a/codes/csharp/chapter_dynamic_programming/unbounded_knapsack.cs b/codes/csharp/chapter_dynamic_programming/unbounded_knapsack.cs index 154fcf3ea8..25131cc599 100644 --- a/codes/csharp/chapter_dynamic_programming/unbounded_knapsack.cs +++ b/codes/csharp/chapter_dynamic_programming/unbounded_knapsack.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_dynamic_programming; public class unbounded_knapsack { /* 完全背包:动态规划 */ - public static int UnboundedKnapsackDP(int[] wgt, int[] val, int cap) { + int UnboundedKnapsackDP(int[] wgt, int[] val, int cap) { int n = wgt.Length; // 初始化 dp 表 int[,] dp = new int[n + 1, cap + 1]; @@ -28,7 +28,7 @@ public static int UnboundedKnapsackDP(int[] wgt, int[] val, int cap) { } /* 完全背包:空间优化后的动态规划 */ - public static int UnboundedKnapsackDPComp(int[] wgt, int[] val, int cap) { + int UnboundedKnapsackDPComp(int[] wgt, int[] val, int cap) { int n = wgt.Length; // 初始化 dp 表 int[] dp = new int[cap + 1]; diff --git a/codes/csharp/chapter_graph/graph_adjacency_list.cs b/codes/csharp/chapter_graph/graph_adjacency_list.cs index f62638e355..4e70234c5d 100644 --- a/codes/csharp/chapter_graph/graph_adjacency_list.cs +++ b/codes/csharp/chapter_graph/graph_adjacency_list.cs @@ -13,7 +13,7 @@ public class GraphAdjList { /* 构造函数 */ public GraphAdjList(Vertex[][] edges) { - this.adjList = []; + adjList = []; // 添加所有顶点和边 foreach (Vertex[] edge in edges) { AddVertex(edge[0]); @@ -23,29 +23,26 @@ public GraphAdjList(Vertex[][] edges) { } /* 获取顶点数量 */ - public int Size() { + int Size() { return adjList.Count; } /* 添加边 */ public void AddEdge(Vertex vet1, Vertex vet2) { - if (!adjList.TryGetValue(vet1, out List? vectors1) - || !adjList.TryGetValue(vet2, out List? vectors2) - || vet1 == vet2) + if (!adjList.ContainsKey(vet1) || !adjList.ContainsKey(vet2) || vet1 == vet2) throw new InvalidOperationException(); - vectors1.Add(vet2); - vectors2.Add(vet1); + // 添加边 vet1 - vet2 + adjList[vet1].Add(vet2); + adjList[vet2].Add(vet1); } /* 删除边 */ public void RemoveEdge(Vertex vet1, Vertex vet2) { - if (!adjList.TryGetValue(vet1, out List? vectors1) - || !adjList.TryGetValue(vet2, out List? vectors2) - || vet1 == vet2) + if (!adjList.ContainsKey(vet1) || !adjList.ContainsKey(vet2) || vet1 == vet2) throw new InvalidOperationException(); // 删除边 vet1 - vet2 - vectors1.Remove(vet2); - vectors2.Remove(vet1); + adjList[vet1].Remove(vet2); + adjList[vet2].Remove(vet1); } /* 添加顶点 */ diff --git a/codes/csharp/chapter_graph/graph_adjacency_matrix.cs b/codes/csharp/chapter_graph/graph_adjacency_matrix.cs index 22f7f6a6f2..5d5933d31b 100644 --- a/codes/csharp/chapter_graph/graph_adjacency_matrix.cs +++ b/codes/csharp/chapter_graph/graph_adjacency_matrix.cs @@ -8,8 +8,8 @@ namespace hello_algo.chapter_graph; /* 基于邻接矩阵实现的无向图类 */ class GraphAdjMat { - readonly List vertices; // 顶点列表,元素代表“顶点值”,索引代表“顶点索引” - readonly List> adjMat; // 邻接矩阵,行列索引对应“顶点索引” + List vertices; // 顶点列表,元素代表“顶点值”,索引代表“顶点索引” + List> adjMat; // 邻接矩阵,行列索引对应“顶点索引” /* 构造函数 */ public GraphAdjMat(int[] vertices, int[][] edges) { @@ -27,7 +27,7 @@ public GraphAdjMat(int[] vertices, int[][] edges) { } /* 获取顶点数量 */ - public int Size() { + int Size() { return vertices.Count; } diff --git a/codes/csharp/chapter_graph/graph_bfs.cs b/codes/csharp/chapter_graph/graph_bfs.cs index 70bf0799d6..32b072bbf6 100644 --- a/codes/csharp/chapter_graph/graph_bfs.cs +++ b/codes/csharp/chapter_graph/graph_bfs.cs @@ -9,7 +9,7 @@ namespace hello_algo.chapter_graph; public class graph_bfs { /* 广度优先遍历 BFS */ // 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点 - public static List GraphBFS(GraphAdjList graph, Vertex startVet) { + List GraphBFS(GraphAdjList graph, Vertex startVet) { // 顶点遍历序列 List res = []; // 哈希表,用于记录已被访问过的顶点 diff --git a/codes/csharp/chapter_graph/graph_dfs.cs b/codes/csharp/chapter_graph/graph_dfs.cs index e29cdff535..f0c5e7a721 100644 --- a/codes/csharp/chapter_graph/graph_dfs.cs +++ b/codes/csharp/chapter_graph/graph_dfs.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_graph; public class graph_dfs { /* 深度优先遍历 DFS 辅助函数 */ - public static void DFS(GraphAdjList graph, HashSet visited, List res, Vertex vet) { + void DFS(GraphAdjList graph, HashSet visited, List res, Vertex vet) { res.Add(vet); // 记录访问顶点 visited.Add(vet); // 标记该顶点已被访问 // 遍历该顶点的所有邻接顶点 @@ -23,7 +23,7 @@ public static void DFS(GraphAdjList graph, HashSet visited, List /* 深度优先遍历 DFS */ // 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点 - public static List GraphDFS(GraphAdjList graph, Vertex startVet) { + List GraphDFS(GraphAdjList graph, Vertex startVet) { // 顶点遍历序列 List res = []; // 哈希表,用于记录已被访问过的顶点 diff --git a/codes/csharp/chapter_greedy/coin_change_greedy.cs b/codes/csharp/chapter_greedy/coin_change_greedy.cs index 5707b9ef0b..693cbeb28c 100644 --- a/codes/csharp/chapter_greedy/coin_change_greedy.cs +++ b/codes/csharp/chapter_greedy/coin_change_greedy.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_greedy; public class coin_change_greedy { /* 零钱兑换:贪心 */ - public static int CoinChangeGreedy(int[] coins, int amt) { + int CoinChangeGreedy(int[] coins, int amt) { // 假设 coins 列表有序 int i = coins.Length - 1; int count = 0; diff --git a/codes/csharp/chapter_greedy/fractional_knapsack.cs b/codes/csharp/chapter_greedy/fractional_knapsack.cs index 253afe3a3c..e2f477b286 100644 --- a/codes/csharp/chapter_greedy/fractional_knapsack.cs +++ b/codes/csharp/chapter_greedy/fractional_knapsack.cs @@ -14,7 +14,7 @@ class Item(int w, int v) { public class fractional_knapsack { /* 分数背包:贪心 */ - public static double FractionalKnapsack(int[] wgt, int[] val, int cap) { + double FractionalKnapsack(int[] wgt, int[] val, int cap) { // 创建物品列表,包含两个属性:重量、价值 Item[] items = new Item[wgt.Length]; for (int i = 0; i < wgt.Length; i++) { diff --git a/codes/csharp/chapter_greedy/max_capacity.cs b/codes/csharp/chapter_greedy/max_capacity.cs index 5f11fca3f2..004841d73d 100644 --- a/codes/csharp/chapter_greedy/max_capacity.cs +++ b/codes/csharp/chapter_greedy/max_capacity.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_greedy; public class max_capacity { /* 最大容量:贪心 */ - public static int MaxCapacity(int[] ht) { + int MaxCapacity(int[] ht) { // 初始化 i, j 分列数组两端 int i = 0, j = ht.Length - 1; // 初始最大容量为 0 diff --git a/codes/csharp/chapter_greedy/max_product_cutting.cs b/codes/csharp/chapter_greedy/max_product_cutting.cs index 1b5c62fa35..f57d9b498a 100644 --- a/codes/csharp/chapter_greedy/max_product_cutting.cs +++ b/codes/csharp/chapter_greedy/max_product_cutting.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_greedy; public class max_product_cutting { /* 最大切分乘积:贪心 */ - public static int MaxProductCutting(int n) { + int MaxProductCutting(int n) { // 当 n <= 3 时,必须切分出一个 1 if (n <= 3) { return 1 * (n - 1); diff --git a/codes/csharp/chapter_hashing/array_hash_map.cs b/codes/csharp/chapter_hashing/array_hash_map.cs index 5df489d279..46c9b10ee1 100644 --- a/codes/csharp/chapter_hashing/array_hash_map.cs +++ b/codes/csharp/chapter_hashing/array_hash_map.cs @@ -14,7 +14,7 @@ class Pair(int key, string val) { /* 基于数组简易实现的哈希表 */ class ArrayHashMap { - private readonly List buckets; + List buckets; public ArrayHashMap() { // 初始化数组,包含 100 个桶 buckets = []; @@ -24,7 +24,7 @@ public ArrayHashMap() { } /* 哈希函数 */ - private static int HashFunc(int key) { + int HashFunc(int key) { int index = key % 100; return index; } diff --git a/codes/csharp/chapter_hashing/hash_map_chaining.cs b/codes/csharp/chapter_hashing/hash_map_chaining.cs index bd9c39758f..3a17e8010c 100644 --- a/codes/csharp/chapter_hashing/hash_map_chaining.cs +++ b/codes/csharp/chapter_hashing/hash_map_chaining.cs @@ -10,8 +10,8 @@ namespace hello_algo.chapter_hashing; class HashMapChaining { int size; // 键值对数量 int capacity; // 哈希表容量 - readonly double loadThres; // 触发扩容的负载因子阈值 - readonly int extendRatio; // 扩容倍数 + double loadThres; // 触发扩容的负载因子阈值 + int extendRatio; // 扩容倍数 List> buckets; // 桶数组 /* 构造方法 */ @@ -27,12 +27,12 @@ public HashMapChaining() { } /* 哈希函数 */ - private int HashFunc(int key) { + int HashFunc(int key) { return key % capacity; } /* 负载因子 */ - private double LoadFactor() { + double LoadFactor() { return (double)size / capacity; } @@ -82,7 +82,7 @@ public void Remove(int key) { } /* 扩容哈希表 */ - private void Extend() { + void Extend() { // 暂存原哈希表 List> bucketsTmp = buckets; // 初始化扩容后的新哈希表 diff --git a/codes/csharp/chapter_hashing/hash_map_open_addressing.cs b/codes/csharp/chapter_hashing/hash_map_open_addressing.cs index e326e68381..719a9b19ac 100644 --- a/codes/csharp/chapter_hashing/hash_map_open_addressing.cs +++ b/codes/csharp/chapter_hashing/hash_map_open_addressing.cs @@ -8,12 +8,12 @@ namespace hello_algo.chapter_hashing; /* 开放寻址哈希表 */ 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() { @@ -22,17 +22,17 @@ public HashMapOpenAddressing() { } /* 哈希函数 */ - 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; // 线性探测,当遇到空桶时跳出 @@ -100,7 +100,7 @@ public void Remove(int key) { } /* 扩容哈希表 */ - private void Extend() { + void Extend() { // 暂存原哈希表 Pair[] bucketsTmp = buckets; // 初始化扩容后的新哈希表 diff --git a/codes/csharp/chapter_hashing/simple_hash.cs b/codes/csharp/chapter_hashing/simple_hash.cs index fa74314bc0..52ad0681a9 100644 --- a/codes/csharp/chapter_hashing/simple_hash.cs +++ b/codes/csharp/chapter_hashing/simple_hash.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_hashing; public class simple_hash { /* 加法哈希 */ - public static int AddHash(string key) { + int AddHash(string key) { long hash = 0; const int MODULUS = 1000000007; foreach (char c in key) { @@ -18,7 +18,7 @@ public static int AddHash(string key) { } /* 乘法哈希 */ - public static int MulHash(string key) { + int MulHash(string key) { long hash = 0; const int MODULUS = 1000000007; foreach (char c in key) { @@ -28,7 +28,7 @@ public static int MulHash(string key) { } /* 异或哈希 */ - public static int XorHash(string key) { + int XorHash(string key) { int hash = 0; const int MODULUS = 1000000007; foreach (char c in key) { @@ -38,7 +38,7 @@ public static int XorHash(string key) { } /* 旋转哈希 */ - public static int RotHash(string key) { + int RotHash(string key) { long hash = 0; const int MODULUS = 1000000007; foreach (char c in key) { diff --git a/codes/csharp/chapter_heap/heap.cs b/codes/csharp/chapter_heap/heap.cs index c2b916fcf9..e822e0bb43 100644 --- a/codes/csharp/chapter_heap/heap.cs +++ b/codes/csharp/chapter_heap/heap.cs @@ -7,13 +7,13 @@ namespace hello_algo.chapter_heap; public class heap { - public static void TestPush(PriorityQueue heap, int val) { + void TestPush(PriorityQueue heap, int val) { heap.Enqueue(val, val); // 元素入堆 Console.WriteLine($"\n元素 {val} 入堆后\n"); PrintUtil.PrintHeap(heap); } - public static void TestPop(PriorityQueue heap) { + void TestPop(PriorityQueue heap) { int val = heap.Dequeue(); // 堆顶元素出堆 Console.WriteLine($"\n堆顶元素 {val} 出堆后\n"); PrintUtil.PrintHeap(heap); diff --git a/codes/csharp/chapter_heap/my_heap.cs b/codes/csharp/chapter_heap/my_heap.cs index da2d5e9083..addf07c6cb 100644 --- a/codes/csharp/chapter_heap/my_heap.cs +++ b/codes/csharp/chapter_heap/my_heap.cs @@ -9,7 +9,7 @@ namespace hello_algo.chapter_heap; /* 大顶堆 */ class MaxHeap { // 使用列表而非数组,这样无须考虑扩容问题 - private readonly List maxHeap; + List maxHeap; /* 构造函数,建立空堆 */ public MaxHeap() { @@ -28,17 +28,17 @@ public MaxHeap(IEnumerable nums) { } /* 获取左子节点索引 */ - static int Left(int i) { + int Left(int i) { return 2 * i + 1; } /* 获取右子节点索引 */ - static int Right(int i) { + int Right(int i) { return 2 * i + 2; } /* 获取父节点索引 */ - static int Parent(int i) { + int Parent(int i) { return (i - 1) / 2; // 向下整除 } diff --git a/codes/csharp/chapter_heap/top_k.cs b/codes/csharp/chapter_heap/top_k.cs index 9427feff9a..72ecfe6f28 100644 --- a/codes/csharp/chapter_heap/top_k.cs +++ b/codes/csharp/chapter_heap/top_k.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_heap; public class top_k { /* 基于堆查找数组中最大的 k 个元素 */ - public static PriorityQueue TopKHeap(int[] nums, int k) { + PriorityQueue TopKHeap(int[] nums, int k) { // 初始化小顶堆 PriorityQueue heap = new(); // 将数组的前 k 个元素入堆 diff --git a/codes/csharp/chapter_searching/binary_search.cs b/codes/csharp/chapter_searching/binary_search.cs index 9c7933330a..34e6defbce 100644 --- a/codes/csharp/chapter_searching/binary_search.cs +++ b/codes/csharp/chapter_searching/binary_search.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_searching; public class binary_search { /* 二分查找(双闭区间) */ - static int BinarySearch(int[] nums, int target) { + int BinarySearch(int[] nums, int target) { // 初始化双闭区间 [0, n-1] ,即 i, j 分别指向数组首元素、尾元素 int i = 0, j = nums.Length - 1; // 循环,当搜索区间为空时跳出(当 i > j 时为空) @@ -26,7 +26,7 @@ static int BinarySearch(int[] nums, int target) { } /* 二分查找(左闭右开) */ - static int BinarySearchLCRO(int[] nums, int target) { + int BinarySearchLCRO(int[] nums, int target) { // 初始化左闭右开 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1 int i = 0, j = nums.Length; // 循环,当搜索区间为空时跳出(当 i = j 时为空) diff --git a/codes/csharp/chapter_searching/binary_search_edge.cs b/codes/csharp/chapter_searching/binary_search_edge.cs index cc880857b4..609daa3b1a 100644 --- a/codes/csharp/chapter_searching/binary_search_edge.cs +++ b/codes/csharp/chapter_searching/binary_search_edge.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_searching; public class binary_search_edge { /* 二分查找最左一个 target */ - public static int BinarySearchLeftEdge(int[] nums, int target) { + int BinarySearchLeftEdge(int[] nums, int target) { // 等价于查找 target 的插入点 int i = binary_search_insertion.BinarySearchInsertion(nums, target); // 未找到 target ,返回 -1 @@ -20,7 +20,7 @@ public static int BinarySearchLeftEdge(int[] nums, int target) { } /* 二分查找最右一个 target */ - public static int BinarySearchRightEdge(int[] nums, int target) { + int BinarySearchRightEdge(int[] nums, int target) { // 转化为查找最左一个 target + 1 int i = binary_search_insertion.BinarySearchInsertion(nums, target + 1); // j 指向最右一个 target ,i 指向首个大于 target 的元素 diff --git a/codes/csharp/chapter_searching/hashing_search.cs b/codes/csharp/chapter_searching/hashing_search.cs index 4e1717c606..6431f6964b 100644 --- a/codes/csharp/chapter_searching/hashing_search.cs +++ b/codes/csharp/chapter_searching/hashing_search.cs @@ -8,14 +8,14 @@ namespace hello_algo.chapter_searching; public class hashing_search { /* 哈希查找(数组) */ - static int HashingSearchArray(Dictionary map, int target) { + int HashingSearchArray(Dictionary map, int target) { // 哈希表的 key: 目标元素,value: 索引 // 若哈希表中无此 key ,返回 -1 return map.GetValueOrDefault(target, -1); } /* 哈希查找(链表) */ - static ListNode? HashingSearchLinkedList(Dictionary map, int target) { + ListNode? HashingSearchLinkedList(Dictionary map, int target) { // 哈希表的 key: 目标节点值,value: 节点对象 // 若哈希表中无此 key ,返回 null diff --git a/codes/csharp/chapter_searching/linear_search.cs b/codes/csharp/chapter_searching/linear_search.cs index 26ee5b2863..f4e10d5f8a 100644 --- a/codes/csharp/chapter_searching/linear_search.cs +++ b/codes/csharp/chapter_searching/linear_search.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_searching; public class linear_search { /* 线性查找(数组) */ - static int LinearSearchArray(int[] nums, int target) { + int LinearSearchArray(int[] nums, int target) { // 遍历数组 for (int i = 0; i < nums.Length; i++) { // 找到目标元素,返回其索引 @@ -20,7 +20,7 @@ static int LinearSearchArray(int[] nums, int target) { } /* 线性查找(链表) */ - static ListNode? LinearSearchLinkedList(ListNode? head, int target) { + ListNode? LinearSearchLinkedList(ListNode? head, int target) { // 遍历链表 while (head != null) { // 找到目标节点,返回之 diff --git a/codes/csharp/chapter_searching/two_sum.cs b/codes/csharp/chapter_searching/two_sum.cs index 1cfbe6918a..5fce6fff3d 100644 --- a/codes/csharp/chapter_searching/two_sum.cs +++ b/codes/csharp/chapter_searching/two_sum.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_searching; public class two_sum { /* 方法一:暴力枚举 */ - public static int[] TwoSumBruteForce(int[] nums, int target) { + int[] TwoSumBruteForce(int[] nums, int target) { int size = nums.Length; // 两层循环,时间复杂度 O(n^2) for (int i = 0; i < size - 1; i++) { @@ -21,7 +21,7 @@ public static int[] TwoSumBruteForce(int[] nums, int target) { } /* 方法二:辅助哈希表 */ - public static int[] TwoSumHashTable(int[] nums, int target) { + int[] TwoSumHashTable(int[] nums, int target) { int size = nums.Length; // 辅助哈希表,空间复杂度 O(n) Dictionary dic = []; diff --git a/codes/csharp/chapter_sorting/bubble_sort.cs b/codes/csharp/chapter_sorting/bubble_sort.cs index bb4db09648..67a154d15c 100644 --- a/codes/csharp/chapter_sorting/bubble_sort.cs +++ b/codes/csharp/chapter_sorting/bubble_sort.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_sorting; public class bubble_sort { /* 冒泡排序 */ - static void BubbleSort(int[] nums) { + void BubbleSort(int[] nums) { // 外循环:未排序区间为 [0, i] for (int i = nums.Length - 1; i > 0; i--) { // 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端 @@ -22,7 +22,7 @@ static void BubbleSort(int[] nums) { } /* 冒泡排序(标志优化)*/ - static void BubbleSortWithFlag(int[] nums) { + void BubbleSortWithFlag(int[] nums) { // 外循环:未排序区间为 [0, i] for (int i = nums.Length - 1; i > 0; i--) { bool flag = false; // 初始化标志位 diff --git a/codes/csharp/chapter_sorting/bucket_sort.cs b/codes/csharp/chapter_sorting/bucket_sort.cs index f95a0566eb..1cd5df43d1 100644 --- a/codes/csharp/chapter_sorting/bucket_sort.cs +++ b/codes/csharp/chapter_sorting/bucket_sort.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_sorting; public class bucket_sort { /* 桶排序 */ - public static void BucketSort(float[] nums) { + void BucketSort(float[] nums) { // 初始化 k = n/2 个桶,预期向每个桶分配 2 个元素 int k = nums.Length / 2; List> buckets = []; diff --git a/codes/csharp/chapter_sorting/counting_sort.cs b/codes/csharp/chapter_sorting/counting_sort.cs index f2f7689823..d410288450 100644 --- a/codes/csharp/chapter_sorting/counting_sort.cs +++ b/codes/csharp/chapter_sorting/counting_sort.cs @@ -9,7 +9,7 @@ namespace hello_algo.chapter_sorting; public class counting_sort { /* 计数排序 */ // 简单实现,无法用于排序对象 - public static void CountingSortNaive(int[] nums) { + void CountingSortNaive(int[] nums) { // 1. 统计数组最大元素 m int m = 0; foreach (int num in nums) { @@ -32,7 +32,7 @@ public static void CountingSortNaive(int[] nums) { /* 计数排序 */ // 完整实现,可排序对象,并且是稳定排序 - static void CountingSort(int[] nums) { + void CountingSort(int[] nums) { // 1. 统计数组最大元素 m int m = 0; foreach (int num in nums) { diff --git a/codes/csharp/chapter_sorting/heap_sort.cs b/codes/csharp/chapter_sorting/heap_sort.cs index b70adecd7f..76be3e1520 100644 --- a/codes/csharp/chapter_sorting/heap_sort.cs +++ b/codes/csharp/chapter_sorting/heap_sort.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_sorting; public class heap_sort { /* 堆的长度为 n ,从节点 i 开始,从顶至底堆化 */ - public static void SiftDown(int[] nums, int n, int i) { + void SiftDown(int[] nums, int n, int i) { while (true) { // 判断节点 i, l, r 中值最大的节点,记为 ma int l = 2 * i + 1; @@ -29,7 +29,7 @@ public static void SiftDown(int[] nums, int n, int i) { } /* 堆排序 */ - public static void HeapSort(int[] nums) { + void HeapSort(int[] nums) { // 建堆操作:堆化除叶节点以外的其他所有节点 for (int i = nums.Length / 2 - 1; i >= 0; i--) { SiftDown(nums, nums.Length, i); diff --git a/codes/csharp/chapter_sorting/insertion_sort.cs b/codes/csharp/chapter_sorting/insertion_sort.cs index aefc89f4bf..78e5206005 100644 --- a/codes/csharp/chapter_sorting/insertion_sort.cs +++ b/codes/csharp/chapter_sorting/insertion_sort.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_sorting; public class insertion_sort { /* 插入排序 */ - static void InsertionSort(int[] nums) { + void InsertionSort(int[] nums) { // 外循环:已排序元素数量为 1, 2, ..., n for (int i = 1; i < nums.Length; i++) { int bas = nums[i], j = i - 1; diff --git a/codes/csharp/chapter_sorting/merge_sort.cs b/codes/csharp/chapter_sorting/merge_sort.cs index 7d06d02bd7..0966e89073 100644 --- a/codes/csharp/chapter_sorting/merge_sort.cs +++ b/codes/csharp/chapter_sorting/merge_sort.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_sorting; public class merge_sort { /* 合并左子数组和右子数组 */ - static void Merge(int[] nums, int left, int mid, int right) { + void Merge(int[] nums, int left, int mid, int right) { // 左子数组区间 [left, mid], 右子数组区间 [mid+1, right] // 创建一个临时数组 tmp ,用于存放合并后的结果 int[] tmp = new int[right - left + 1]; @@ -35,7 +35,7 @@ static void Merge(int[] nums, int left, int mid, int right) { } /* 归并排序 */ - static void MergeSort(int[] nums, int left, int right) { + void MergeSort(int[] nums, int left, int right) { // 终止条件 if (left >= right) return; // 当子数组长度为 1 时终止递归 // 划分阶段 diff --git a/codes/csharp/chapter_sorting/radix_sort.cs b/codes/csharp/chapter_sorting/radix_sort.cs index e960071865..4c6c8f337d 100644 --- a/codes/csharp/chapter_sorting/radix_sort.cs +++ b/codes/csharp/chapter_sorting/radix_sort.cs @@ -8,13 +8,13 @@ namespace hello_algo.chapter_sorting; public class radix_sort { /* 获取元素 num 的第 k 位,其中 exp = 10^(k-1) */ - static int Digit(int num, int exp) { + int Digit(int num, int exp) { // 传入 exp 而非 k 可以避免在此重复执行昂贵的次方计算 return (num / exp) % 10; } /* 计数排序(根据 nums 第 k 位排序) */ - static void CountingSortDigit(int[] nums, int exp) { + void CountingSortDigit(int[] nums, int exp) { // 十进制的位范围为 0~9 ,因此需要长度为 10 的桶 int[] counter = new int[10]; int n = nums.Length; @@ -42,7 +42,7 @@ static void CountingSortDigit(int[] nums, int exp) { } /* 基数排序 */ - static void RadixSort(int[] nums) { + void RadixSort(int[] nums) { // 获取数组的最大元素,用于判断最大位数 int m = int.MinValue; foreach (int num in nums) { diff --git a/codes/csharp/chapter_sorting/selection_sort.cs b/codes/csharp/chapter_sorting/selection_sort.cs index 4635a33f52..962660dec3 100644 --- a/codes/csharp/chapter_sorting/selection_sort.cs +++ b/codes/csharp/chapter_sorting/selection_sort.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_sorting; public class selection_sort { /* 选择排序 */ - public static void SelectionSort(int[] nums) { + void SelectionSort(int[] nums) { int n = nums.Length; // 外循环:未排序区间为 [i, n-1] for (int i = 0; i < n - 1; i++) { diff --git a/codes/csharp/chapter_stack_and_queue/array_deque.cs b/codes/csharp/chapter_stack_and_queue/array_deque.cs index 5cd03958d9..23060fc43d 100644 --- a/codes/csharp/chapter_stack_and_queue/array_deque.cs +++ b/codes/csharp/chapter_stack_and_queue/array_deque.cs @@ -8,18 +8,18 @@ namespace hello_algo.chapter_stack_and_queue; /* 基于环形数组实现的双向队列 */ public 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; } @@ -34,7 +34,7 @@ public bool IsEmpty() { } /* 计算环形数组索引 */ - private int Index(int i) { + int Index(int i) { // 通过取余操作实现数组首尾相连 // 当 i 越过数组尾部后,回到头部 // 当 i 越过数组头部后,回到尾部 diff --git a/codes/csharp/chapter_stack_and_queue/array_queue.cs b/codes/csharp/chapter_stack_and_queue/array_queue.cs index 161cc3f74e..b32622f51e 100644 --- a/codes/csharp/chapter_stack_and_queue/array_queue.cs +++ b/codes/csharp/chapter_stack_and_queue/array_queue.cs @@ -8,9 +8,9 @@ namespace hello_algo.chapter_stack_and_queue; /* 基于环形数组实现的队列 */ 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]; @@ -18,7 +18,7 @@ public ArrayQueue(int capacity) { } /* 获取队列的容量 */ - public int Capacity() { + int Capacity() { return nums.Length; } diff --git a/codes/csharp/chapter_stack_and_queue/array_stack.cs b/codes/csharp/chapter_stack_and_queue/array_stack.cs index 558efcaaf8..4f89b65e27 100644 --- a/codes/csharp/chapter_stack_and_queue/array_stack.cs +++ b/codes/csharp/chapter_stack_and_queue/array_stack.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_stack_and_queue; /* 基于数组实现的栈 */ class ArrayStack { - private readonly List stack; + List stack; public ArrayStack() { // 初始化列表(动态数组) stack = []; diff --git a/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs b/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs index 51586fbc83..63cc409b26 100644 --- a/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs +++ b/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs @@ -15,8 +15,8 @@ public class ListNode(int val) { /* 基于双向链表实现的双向队列 */ public class LinkedListDeque { - private ListNode? front, rear; // 头节点 front, 尾节点 rear - private int queSize = 0; // 双向队列的长度 + ListNode? front, rear; // 头节点 front, 尾节点 rear + int queSize = 0; // 双向队列的长度 public LinkedListDeque() { front = null; @@ -34,7 +34,7 @@ public bool IsEmpty() { } /* 入队操作 */ - private void Push(int num, bool isFront) { + void Push(int num, bool isFront) { ListNode node = new(num); // 若链表为空,则令 front, rear 都指向 node if (IsEmpty()) { @@ -70,7 +70,7 @@ public void PushLast(int num) { } /* 出队操作 */ - private int? Pop(bool isFront) { + int? Pop(bool isFront) { if (IsEmpty()) throw new Exception(); int? val; diff --git a/codes/csharp/chapter_stack_and_queue/linkedlist_queue.cs b/codes/csharp/chapter_stack_and_queue/linkedlist_queue.cs index 37bb3a21cb..59d98a53f5 100644 --- a/codes/csharp/chapter_stack_and_queue/linkedlist_queue.cs +++ b/codes/csharp/chapter_stack_and_queue/linkedlist_queue.cs @@ -8,8 +8,8 @@ namespace hello_algo.chapter_stack_and_queue; /* 基于链表实现的队列 */ class LinkedListQueue { - private ListNode? front, rear; // 头节点 front ,尾节点 rear - private int queSize = 0; + ListNode? front, rear; // 头节点 front ,尾节点 rear + int queSize = 0; public LinkedListQueue() { front = null; diff --git a/codes/csharp/chapter_stack_and_queue/linkedlist_stack.cs b/codes/csharp/chapter_stack_and_queue/linkedlist_stack.cs index ab5c058a98..c1b36478bd 100644 --- a/codes/csharp/chapter_stack_and_queue/linkedlist_stack.cs +++ b/codes/csharp/chapter_stack_and_queue/linkedlist_stack.cs @@ -8,8 +8,8 @@ namespace hello_algo.chapter_stack_and_queue; /* 基于链表实现的栈 */ class LinkedListStack { - private ListNode? stackPeek; // 将头节点作为栈顶 - private int stkSize = 0; // 栈的长度 + ListNode? stackPeek; // 将头节点作为栈顶 + int stkSize = 0; // 栈的长度 public LinkedListStack() { stackPeek = null; diff --git a/codes/csharp/chapter_tree/array_binary_tree.cs b/codes/csharp/chapter_tree/array_binary_tree.cs index aa2e0ba8b2..63acc73804 100644 --- a/codes/csharp/chapter_tree/array_binary_tree.cs +++ b/codes/csharp/chapter_tree/array_binary_tree.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_tree; /* 数组表示下的二叉树类 */ public class ArrayBinaryTree(List arr) { - private readonly List tree = new(arr); + List tree = new(arr); /* 节点数量 */ public int Size() { @@ -50,7 +50,7 @@ public List LevelOrder() { } /* 深度优先遍历 */ - private void DFS(int i, string order, List res) { + void DFS(int i, string order, List res) { // 若为空位,则返回 if (!Val(i).HasValue) return; diff --git a/codes/csharp/chapter_tree/avl_tree.cs b/codes/csharp/chapter_tree/avl_tree.cs index 1a072c00e9..d40d9ebe07 100644 --- a/codes/csharp/chapter_tree/avl_tree.cs +++ b/codes/csharp/chapter_tree/avl_tree.cs @@ -11,19 +11,19 @@ class AVLTree { public TreeNode? root; // 根节点 /* 获取节点高度 */ - public static int Height(TreeNode? node) { + int Height(TreeNode? node) { // 空节点高度为 -1 ,叶节点高度为 0 return node == null ? -1 : node.height; } /* 更新节点高度 */ - private static void UpdateHeight(TreeNode node) { + void UpdateHeight(TreeNode node) { // 节点高度等于最高子树高度 + 1 node.height = Math.Max(Height(node.left), Height(node.right)) + 1; } /* 获取平衡因子 */ - public static int BalanceFactor(TreeNode? node) { + public int BalanceFactor(TreeNode? node) { // 空节点平衡因子为 0 if (node == null) return 0; // 节点平衡因子 = 左子树高度 - 右子树高度 @@ -31,7 +31,7 @@ public static int BalanceFactor(TreeNode? node) { } /* 右旋操作 */ - static TreeNode? RightRotate(TreeNode? node) { + TreeNode? RightRotate(TreeNode? node) { TreeNode? child = node?.left; TreeNode? grandChild = child?.right; // 以 child 为原点,将 node 向右旋转 @@ -45,7 +45,7 @@ public static int BalanceFactor(TreeNode? node) { } /* 左旋操作 */ - static TreeNode? LeftRotate(TreeNode? node) { + TreeNode? LeftRotate(TreeNode? node) { TreeNode? child = node?.right; TreeNode? grandChild = child?.left; // 以 child 为原点,将 node 向左旋转 @@ -59,7 +59,7 @@ public static int BalanceFactor(TreeNode? node) { } /* 执行旋转操作,使该子树重新恢复平衡 */ - static TreeNode? Rotate(TreeNode? node) { + TreeNode? Rotate(TreeNode? node) { // 获取节点 node 的平衡因子 int balanceFactorInt = BalanceFactor(node); // 左偏树 @@ -94,7 +94,7 @@ public void Insert(int val) { } /* 递归插入节点(辅助方法) */ - private static TreeNode? InsertHelper(TreeNode? node, int val) { + TreeNode? InsertHelper(TreeNode? node, int val) { if (node == null) return new TreeNode(val); /* 1. 查找插入位置,并插入节点 */ if (val < node.val) @@ -116,7 +116,7 @@ public void Remove(int val) { } /* 递归删除节点(辅助方法) */ - private static TreeNode? RemoveHelper(TreeNode? node, int val) { + TreeNode? RemoveHelper(TreeNode? node, int val) { if (node == null) return null; /* 1. 查找节点,并删除之 */ if (val < node.val) diff --git a/codes/csharp/chapter_tree/binary_tree_bfs.cs b/codes/csharp/chapter_tree/binary_tree_bfs.cs index 84e247b366..da1509802f 100644 --- a/codes/csharp/chapter_tree/binary_tree_bfs.cs +++ b/codes/csharp/chapter_tree/binary_tree_bfs.cs @@ -9,7 +9,7 @@ namespace hello_algo.chapter_tree; public class binary_tree_bfs { /* 层序遍历 */ - public static List LevelOrder(TreeNode root) { + List LevelOrder(TreeNode root) { // 初始化队列,加入根节点 Queue queue = new(); queue.Enqueue(root); diff --git a/codes/csharp/chapter_tree/binary_tree_dfs.cs b/codes/csharp/chapter_tree/binary_tree_dfs.cs index 8ff316d9be..4c1a3d50a0 100644 --- a/codes/csharp/chapter_tree/binary_tree_dfs.cs +++ b/codes/csharp/chapter_tree/binary_tree_dfs.cs @@ -7,7 +7,7 @@ namespace hello_algo.chapter_tree; public class binary_tree_dfs { - readonly List list = []; + List list = []; /* 前序遍历 */ void PreOrder(TreeNode? root) { diff --git a/codes/csharp/utils/TreeNode.cs b/codes/csharp/utils/TreeNode.cs index 6d3ba46358..6d63dfb110 100644 --- a/codes/csharp/utils/TreeNode.cs +++ b/codes/csharp/utils/TreeNode.cs @@ -30,7 +30,7 @@ public class TreeNode(int? x) { // \——— 8 /* 将列表反序列化为二叉树:递归 */ - private static TreeNode? ListToTreeDFS(List arr, int i) { + static TreeNode? ListToTreeDFS(List arr, int i) { if (i < 0 || i >= arr.Count || !arr[i].HasValue) { return null; } @@ -47,7 +47,7 @@ public class TreeNode(int? x) { } /* 将二叉树序列化为列表:递归 */ - private static void TreeToListDFS(TreeNode? root, int i, List res) { + static void TreeToListDFS(TreeNode? root, int i, List res) { if (root == null) return; while (i >= res.Count) { From 3c66a5f8b008920c079f655d3d9fe1b8b043fe70 Mon Sep 17 00:00:00 2001 From: Yudong Jin Date: Sun, 26 Nov 2023 23:03:06 +0800 Subject: [PATCH 06/10] Update binary_search_insertion.cs --- codes/csharp/chapter_searching/binary_search_insertion.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codes/csharp/chapter_searching/binary_search_insertion.cs b/codes/csharp/chapter_searching/binary_search_insertion.cs index af4c1d21f8..aedb46ceb9 100644 --- a/codes/csharp/chapter_searching/binary_search_insertion.cs +++ b/codes/csharp/chapter_searching/binary_search_insertion.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_searching; public class binary_search_insertion { /* 二分查找插入点(无重复元素) */ - public static int BinarySearchInsertionSimple(int[] nums, int target) { + public 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 @@ -25,7 +25,7 @@ public static int BinarySearchInsertionSimple(int[] nums, int target) { } /* 二分查找插入点(存在重复元素) */ - public static int BinarySearchInsertion(int[] nums, int target) { + public 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 From 9bccd3258589ac00b53173e8729536e433571e41 Mon Sep 17 00:00:00 2001 From: Yudong Jin Date: Sun, 26 Nov 2023 23:07:57 +0800 Subject: [PATCH 07/10] Update binary_search_insertion.cs --- codes/csharp/chapter_searching/binary_search_insertion.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codes/csharp/chapter_searching/binary_search_insertion.cs b/codes/csharp/chapter_searching/binary_search_insertion.cs index aedb46ceb9..1f60d29b8d 100644 --- a/codes/csharp/chapter_searching/binary_search_insertion.cs +++ b/codes/csharp/chapter_searching/binary_search_insertion.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_searching; public class binary_search_insertion { /* 二分查找插入点(无重复元素) */ - public int BinarySearchInsertionSimple(int[] nums, int target) { + 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 @@ -25,7 +25,7 @@ public int BinarySearchInsertionSimple(int[] nums, int target) { } /* 二分查找插入点(存在重复元素) */ - public int BinarySearchInsertion(int[] nums, int target) { + 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 From fe8a3d1601baa2e0470f7bb1fa75bd37f8921fe5 Mon Sep 17 00:00:00 2001 From: Yudong Jin Date: Sun, 26 Nov 2023 23:13:16 +0800 Subject: [PATCH 08/10] Update binary_search_edge.cs --- codes/csharp/chapter_searching/binary_search_edge.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codes/csharp/chapter_searching/binary_search_edge.cs b/codes/csharp/chapter_searching/binary_search_edge.cs index 609daa3b1a..cc880857b4 100644 --- a/codes/csharp/chapter_searching/binary_search_edge.cs +++ b/codes/csharp/chapter_searching/binary_search_edge.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_searching; public class binary_search_edge { /* 二分查找最左一个 target */ - int BinarySearchLeftEdge(int[] nums, int target) { + public static int BinarySearchLeftEdge(int[] nums, int target) { // 等价于查找 target 的插入点 int i = binary_search_insertion.BinarySearchInsertion(nums, target); // 未找到 target ,返回 -1 @@ -20,7 +20,7 @@ int BinarySearchLeftEdge(int[] nums, int target) { } /* 二分查找最右一个 target */ - int BinarySearchRightEdge(int[] nums, int target) { + public static int BinarySearchRightEdge(int[] nums, int target) { // 转化为查找最左一个 target + 1 int i = binary_search_insertion.BinarySearchInsertion(nums, target + 1); // j 指向最右一个 target ,i 指向首个大于 target 的元素 From ae1417ab18713fa1fe41bf928accc9bcd7539be6 Mon Sep 17 00:00:00 2001 From: Yudong Jin Date: Sun, 26 Nov 2023 23:16:09 +0800 Subject: [PATCH 09/10] Update binary_search_insertion.cs --- codes/csharp/chapter_searching/binary_search_insertion.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codes/csharp/chapter_searching/binary_search_insertion.cs b/codes/csharp/chapter_searching/binary_search_insertion.cs index 1f60d29b8d..af4c1d21f8 100644 --- a/codes/csharp/chapter_searching/binary_search_insertion.cs +++ b/codes/csharp/chapter_searching/binary_search_insertion.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_searching; public class binary_search_insertion { /* 二分查找插入点(无重复元素) */ - int BinarySearchInsertionSimple(int[] nums, int target) { + public static 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 @@ -25,7 +25,7 @@ int BinarySearchInsertionSimple(int[] nums, int target) { } /* 二分查找插入点(存在重复元素) */ - int BinarySearchInsertion(int[] nums, int target) { + public static 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 From d113469ce2b8eed9372a6c35053ef97217b242e7 Mon Sep 17 00:00:00 2001 From: Yudong Jin Date: Sun, 26 Nov 2023 23:16:55 +0800 Subject: [PATCH 10/10] Update binary_search_edge.cs --- codes/csharp/chapter_searching/binary_search_edge.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codes/csharp/chapter_searching/binary_search_edge.cs b/codes/csharp/chapter_searching/binary_search_edge.cs index cc880857b4..609daa3b1a 100644 --- a/codes/csharp/chapter_searching/binary_search_edge.cs +++ b/codes/csharp/chapter_searching/binary_search_edge.cs @@ -8,7 +8,7 @@ namespace hello_algo.chapter_searching; public class binary_search_edge { /* 二分查找最左一个 target */ - public static int BinarySearchLeftEdge(int[] nums, int target) { + int BinarySearchLeftEdge(int[] nums, int target) { // 等价于查找 target 的插入点 int i = binary_search_insertion.BinarySearchInsertion(nums, target); // 未找到 target ,返回 -1 @@ -20,7 +20,7 @@ public static int BinarySearchLeftEdge(int[] nums, int target) { } /* 二分查找最右一个 target */ - public static int BinarySearchRightEdge(int[] nums, int target) { + int BinarySearchRightEdge(int[] nums, int target) { // 转化为查找最左一个 target + 1 int i = binary_search_insertion.BinarySearchInsertion(nums, target + 1); // j 指向最右一个 target ,i 指向首个大于 target 的元素