mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-27 00:26:28 +08:00
f62256bee1
* Modify method name to PascalCase(array and linked list) * Modify method name to PascalCase(backtracking) * Modify method name to PascalCase(computational complexity) * Modify method name to PascalCase(divide and conquer) * Modify method name to PascalCase(dynamic programming) * Modify method name to PascalCase(graph) * Modify method name to PascalCase(greedy) * Modify method name to PascalCase(hashing) * Modify method name to PascalCase(heap) * Modify method name to PascalCase(searching) * Modify method name to PascalCase(sorting) * Modify method name to PascalCase(stack and queue) * Modify method name to PascalCase(tree) * local check
52 lines
1.6 KiB
C#
52 lines
1.6 KiB
C#
/**
|
|
* File: two_sum.cs
|
|
* Created Time: 2022-12-23
|
|
* Author: haptear (haptear@hotmail.com)
|
|
*/
|
|
|
|
namespace hello_algo.chapter_searching;
|
|
|
|
public class two_sum {
|
|
/* 方法一:暴力枚举 */
|
|
public static 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 Array.Empty<int>();
|
|
}
|
|
|
|
/* 方法二:辅助哈希表 */
|
|
public static int[] TwoSumHashTable(int[] nums, int target) {
|
|
int size = nums.Length;
|
|
// 辅助哈希表,空间复杂度 O(n)
|
|
Dictionary<int, int> dic = new();
|
|
// 单层循环,时间复杂度 O(n)
|
|
for (int i = 0; i < size; i++) {
|
|
if (dic.ContainsKey(target - nums[i])) {
|
|
return new int[] { dic[target - nums[i]], i };
|
|
}
|
|
dic.Add(nums[i], i);
|
|
}
|
|
return Array.Empty<int>();
|
|
}
|
|
|
|
[Test]
|
|
public void Test() {
|
|
// ======= Test Case =======
|
|
int[] nums = { 2, 7, 11, 15 };
|
|
int target = 13;
|
|
|
|
// ====== Driver Code ======
|
|
// 方法一
|
|
int[] res = TwoSumBruteForce(nums, target);
|
|
Console.WriteLine("方法一 res = " + string.Join(",", res));
|
|
// 方法二
|
|
res = TwoSumHashTable(nums, target);
|
|
Console.WriteLine("方法二 res = " + string.Join(",", res));
|
|
}
|
|
}
|