给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 +
7 = 9 所以返回 [0, 1]
一.目前我只会暴力破解法: 遍历每个元素 xx,并查找是否存在一个值与 target - xtarget−x
相等的目标元素。
public static int[] twoSum(int[] nums, int target) {
for(int i=0;i<nums.length;i++) {
for(int j=0;j<nums.length;j++) {
if(nums[i]+nums[j]==target) {
return new int[]{
i,j};
}
}
}
return new int[] {
-1,1};
}
二.循环一遍哈希表(看答案的):
在进行迭代并将元素插入到表中的同时,我们还会回过头来检查表中是否已经存在当前元素所对应的目标元素。如果它存在,那我们已经找到了对应解,并立即将其返回。
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] {
map.get(complement), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
三.循环两遍哈希表(看答案的): 哈希表支持以 近似 恒定的时间进行快速查找,正好适合。
两次迭代:第一次迭代,将每个元素的值和它的索引添加到表中。第二次迭代,检查每个元素所对应的目标元素(target - nums[i]target−nums[i])是否存在于表中。
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] {
i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}