LeetCode 求和, 给一个数组,和一个目标数,在这个数组中找到两个数的和 是这个目标数, 返回索引
两层循环的时间复杂度太高
用hashtable需要进行装箱和拆箱操作
所以最后用dictionary了
public int[] TwoSum(int[] nums, int target)
{
if(nums == null)
{
return null;
}
#region solution 1
//for (int i = 0; i < nums.Length; ++i)
//{
// if (nums[i] >= target)
// {
// continue;
// }
// for (int j = 0; j < nums.Length; ++j)
// {
// if(i == j)
// {
// continue;
// }
// else
// {
// if (nums[i] + nums[j] == target)
// {
// return new int[] { i, j };
// }
// }
// }
//}
#endregion
//Hashtable hash = new Hashtable();
//for (int i = 0; i < nums.Length; ++i)
//{
// hash.Add(nums[i], i);
//}
//for (int i = 0; i < nums.Length; ++i)
//{
// int res = target - nums[i];
// if (hash.ContainsKey(res))
// {
// int numIndex = (int)hash[res];
// if (numIndex != i)
// {
// return new int[] { i, numIndex };
// }
// }
//}
Dictionary<int, int> dict = new Dictionary<int, int>();
for (int i = 0; i < nums.Length; ++i)
{
if(dict.ContainsKey(nums[i]) == false)
dict.Add(nums[i], i);
}
for (int i = 0; i < nums.Length; ++i)
{
int res = target - nums[i];
if(dict.ContainsKey(res) && dict[res] != i)
{
return new int[] { i, dict[res] };
}
}
return null;
}