给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
①暴力解法:
利用for循环遍历每个数组元素 ,并查找是否存在一个值与其中另一个元素相加等于 target
class Solution1 {
public 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[j] == target - nums[i]) {
return new int[]{i, j};
}
}
}
return null;
}
}
②利用HashMap特性,将元素当成Key,对应元素下标当成Value
先判断HashMap中是否存在一个值与数组的第一个元素相加等于target
如果没有,则将数组的第一个元素放入HashMap中
再判断HashMap中是否存在一个值与数组第二个元素相加等于target
如果没有,则将数组的第二个元素放入HashMap中
…
而如果存在,则返回对应的解
class Solution2 {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> hm = new HashMap<>();
for(int i = 0; i < nums.length; i++){
int num = target - nums[i];
if(hm.containsKey(num)){
return new int[]{hm.get(num), i};
}
else hm.put(nums[i], i);
}
return null;
}
}