题目:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解答:
C#
class Program
{
static void Main(string[] args)
{
int[] nums = { 2, 7, 11, 15 };
int target = 9;
var arr = OneSum(nums, target);
//var arr = TwoSum(nums, target);
//var arr = ThreeSum(nums, target);
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
Console.ReadKey();
}
//第一种方法
public static int[] OneSum(int[] nums, int target)
{
for (int i = 0; i < nums.Length; i++)
{
for (int j = i + 1; j < nums.Length; j++)
{
if (nums[j] == target - nums[i])
{
return new int[] { i, j };
}
}
}
throw new Exception("No two sum solution");
}
//第二种方法
public static int[] TwoSum(int[] nums, int target)
{
Hashtable ht = new Hashtable();
for (int i = 0; i < nums.Length; i++)
{
ht.Add(nums[i], i);
}
for (int i = 0; i < nums.Length; i++)
{
int complent = target - nums[i];
if (ht.ContainsKey(complent) && Convert.ToInt32(ht[complent]) != i)
{
return new int[] { i, Convert.ToInt32(ht[complent]) };
}
}
throw new Exception("No two sum solution");
}
//第三种方法
public static int[] ThreeSum(int[] nums, int target)
{
Hashtable ht = new Hashtable();
for (int i = 0; i < nums.Length; i++)
{
int complent = target - nums[i];
if (ht.ContainsKey(complent))
{
return new int[] { Convert.ToInt32(ht[complent]), i};
}
ht.Add(nums[i], i);
}
throw new Exception("No two sum solution");
}
}