给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
package Hash;
import java.util.Arrays;
import java.util.HashMap;
public class LeetCode1_01 {
public static void main(String[] args) {
int[] nums = {1,4,5,9,10,7};
int target = 11;
/*int[] nums = {3,2,4};
int target = 6;*/
int[] result = twoSum(nums,target);
System.out.println(Arrays.toString(result));
}
public static int[] twoSum(int[] nums , int target){
/*
HashMap是键值对组合,本题目要返回下标,而要匹配的是元素值,故可以用HashMap实现。
(一般来说,Key是唯一的,但本题目中可以把元素值作为Key。
因为我们只关心第一个出现的元素与后面出现的元素之和是否=target。
且,题目中讲每种输入只对应一个答案。即使数组中有重复的元素,也只有一对元素满足条件。)
*/
//定义一个新的HashMap用来存储数组中的元素值和它的下标。
HashMap<Integer, Integer> hashMap = new HashMap<>();
// int[] res = new int[2];
//循环遍历数组,并把数组中的元素存储到HashMap中
for (int i = 0; i < nums.length; i++) {
int temp = target - nums[i];
if (hashMap.containsKey(temp)){
/*temp是与已经在map中的元素查询匹配,比如map中已经存了{1,4,5,9},此时,循环遍历到i=4,而我们的temp是10,
hashMap.get(temp)返回的是先于元素遍历到的元素的下标,i是当前元素下标,
这样前面的元素的下标就小于等于第二个元素的下标
*/
return new int[]{hashMap.get(temp),i};
// return new int[]{temp,nums[i]};//这是返回的是元素的值,发现确实如上述下标一致
// res[0] = hashMap.get(temp);
// res[1] = i;
}
hashMap.put(nums[i],i);//得到元素在map中应是()
}
//定义一个临时变量temp,代表后面出现的元素,看是否与前面的元素和等于目标
//判断map中是否有与temp相等的元素,如果是返回其下标。
//return res;
//throw new IllegalArgumentException("");
return null;
}
}
package Array;
import java.util.Arrays;
public class LeetCode1_02 {
public static void main(String[] args) {
int[] nums = {1,4,5,9,10,7};
int target = 11;
int[] result = twoSum(nums,target);
System.out.println(Arrays.toString(result));
}
public static int[] twoSum(int[] nums , int target){
for (int i = 0; i < nums.length; i++) {
for (int j = i+1; j <nums.length ; j++) {
if (nums[i] +nums[j] ==target){
return new int[]{i,j};
}
}
}
return null;
}
}