题目
1.两数之和
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案,并且你不能使用两次相同的元素。
你可以按任意顺序返回答案。
具体实现
暴力求解
思路及算法:
枚举数组中的每一个数 x,寻找数组中是否存在 target - x,即两数之和等于目标值。
此处想到的优化策略是,二层循环时(即 int j)可以从当前 i 后一位进行判断,因为第一遍循环时,已经判断过 i 和 j 的和了,反过来不再进行判断,也就提升了代码执行效率。
int[] nums = new int[] { 2, 7, 11, 15 };
int[] nums1 = new int[] { 3, 2, 4 };
int[] nums2 = new int[] { 3, 3 };
private int[] SumTwoNumber(int[] nums, int target)
{
int[] result = new int[2];
for (int i = 0; i < nums.Length - 1; i++)
{
for (int j = i + 1; j < nums.Length; j++)
{
if (nums[i] + nums[j] == target)
{
result[0] = i;
result[1] = j;
return result;
}
}
}
return result;
}
哈希表求解
思路及算法:
1、循环遍历数组,创建哈希表进行存储
2、判断此时哈希表中是否存在 target - nums[i] (即目标值减去当前遍历值)
若存在,可以直接返回target - nums[i] (即目标值减去当前遍历值)的索引 和当前值的索引
若不存在,将当前值添加到哈希表中(需要判断是否有重复数据)
int[] nums = new int[] { 2, 7, 11, 15 };
int[] nums1 = new int[] { 3, 2, 4 };
int[] nums2 = new int[] { 3, 3 };
private int[] SumTwoNumber2(int[] nums, int target)
{
Dictionary<int, int> result = new Dictionary<int, int>();
for (int i = 0; i < nums.Length; i++)
{
if (result.ContainsKey(target - nums[i]))
{
return new int[] { result[target - nums[i]], i };
}
else
{
result.TryAdd(nums[i], i);
}
}
return null;
}