mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-16 00:46:06 +00:00
feat(csharp) .NET 8.0 code migration (#966)
* .net 8.0 migration * update docs * revert change * revert change and update appendix docs * remove static * Update binary_search_insertion.cs * Update binary_search_insertion.cs * Update binary_search_edge.cs * Update binary_search_insertion.cs * Update binary_search_edge.cs --------- Co-authored-by: Yudong Jin <krahets@163.com>
This commit is contained in:
@@ -8,37 +8,37 @@ 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++) {
|
||||
for (int j = i + 1; j < size; j++) {
|
||||
if (nums[i] + nums[j] == target)
|
||||
return new int[] { i, j };
|
||||
return [i, j];
|
||||
}
|
||||
}
|
||||
return Array.Empty<int>();
|
||||
return [];
|
||||
}
|
||||
|
||||
/* 方法二:辅助哈希表 */
|
||||
public static int[] TwoSumHashTable(int[] nums, int target) {
|
||||
int[] TwoSumHashTable(int[] nums, int target) {
|
||||
int size = nums.Length;
|
||||
// 辅助哈希表,空间复杂度 O(n)
|
||||
Dictionary<int, int> dic = new();
|
||||
Dictionary<int, int> dic = [];
|
||||
// 单层循环,时间复杂度 O(n)
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (dic.ContainsKey(target - nums[i])) {
|
||||
return new int[] { dic[target - nums[i]], i };
|
||||
return [dic[target - nums[i]], i];
|
||||
}
|
||||
dic.Add(nums[i], i);
|
||||
}
|
||||
return Array.Empty<int>();
|
||||
return [];
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
// ======= Test Case =======
|
||||
int[] nums = { 2, 7, 11, 15 };
|
||||
int[] nums = [2, 7, 11, 15];
|
||||
int target = 13;
|
||||
|
||||
// ====== Driver Code ======
|
||||
|
||||
Reference in New Issue
Block a user