1. 两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
方法一:直接暴力求解
列出数组中的每一个数 x,查找数组中是否存在 target - x。
遍历整个数组寻找 target - x 时,每一个位于 x 之前的元素都已经和 x 匹配过,所以我们只需要在 x 后面的元素中寻找 target - x。
代码如下:
public int[] twoSum(int[] nums,int target){
int n = nums.length;
for (int i=0;i<n;++i){
for (int j=i+1;j<n;++j){
if (nums[i]+nums[j] == target){
return new int[]{i,j};
}
}
}
return new int[0];
}
方法二:哈希表
使用哈希表,可以将寻找 target - x 的时间复杂度降低。
对于每一个 x,我们首先查询哈希表中是否存在 target - x,然后将 x 插入到哈希表中,即可保证不会让 x 和自己匹配。
代码如下:
public int[] twoSum1(int[] nums,int target){
Map<Integer,Integer> hash = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
if (hash.containsKey(target - nums[i])){
return new int[]{hash.get(target-nums[i]),i};
}
hash.put(nums[i],i);
}
return new int[0];
}