# C#LeetCode刷题之#1-两数之和（Two Sum）

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

```public class Program {

public static void Main(string[] args) {
int[] nums = { 2, 7, 11, 15 };

var res = TwoSum(nums, 9);
var res2 = TwoSum2(nums, 9);

Console.WriteLine(\$"[{res[0]},{res[1]}]");
Console.WriteLine(\$"[{res2[0]},{res2[1]}]");

}

public static int[] TwoSum(int[] nums, int target) {
//类似于冒泡，双循环比较2个数的和与目标值是否相等
for (int i = 0; i < nums.Length; i++) {
for (int j = i + 1; j < nums.Length; j++) {
if (nums[i] + nums[j] == target) {
return new int[] { i, j };
}
}
}
//找不到时抛出异常
throw new ArgumentException();
}

public static int[] TwoSum2(int[] nums, int target) {
//用数组中的值做key，索引做value存下所有值
var dictionary = new Dictionary<int, int>();
for (int i = 0; i < nums.Length; i++) {
//记录差值
int complement = target - nums[i];
//若字典中已经存在这个值，说明匹配成功
if (dictionary.ContainsKey(complement)) {
return new int[] { dictionary[complement], i };
}
//记录索引
dictionary[nums[i]] = i;
}
//找不到时抛出异常
throw new ArgumentException();
}

}```

```[0,1]
[0,1]```