leetCode-2-两数之和 题目 你的鼓励也是我创作的动力
- Posted by 微博@Yangsc_o
- 原创文章,版权声明:自由转载-非商用-非衍生-保持署名 | Creative Commons BY-NC-ND 3.0
本题是leetcode,地址:1. 两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解题思路:
两遍哈希表
一个简单的实现使用了两次迭代。在第一次迭代中,我们将每个元素的值和它的索引添加到表中。然后,在第二次迭代中,我们将检查每个元素所对应的目标元素(target - nums[i]target−nums[i])是否存在于表中。需要注意的是该目标元素不能是 nums[i]nums[i] 本身!
一遍Hash
在进行迭代并将元素插入到表中的同时,我们还会回过头来检查表中是否已经存在当前元素所对应的目标元素。如果它存在,那我们已经找到了对应解,并立即将其返回。
code
public class LeetCode2 {
public static int[] twoSum(int[] nums, int target) {
int[] res = new int[]{-1,-1};
Map<Integer,Integer> numsMap = new HashMap<>(8);
for(int i = 0; i < nums.length; i ++) {
int value = nums[i];
numsMap.put(value,i);
}
for(int i = 0; i < nums.length; i ++) {
int value = nums[i];
Integer index = numsMap.get(target - value);
if(index != null && index != i) {
res[0] = i;
res[1] = index;
break;
}
}
return res;
}
public static int[] twoSum2(int[] nums, int target) {
int[] res = new int[]{-1,-1};
Map<Integer,Integer> numsMap = new HashMap<>(8);
for(int i = 0; i < nums.length; i ++) {
int value = nums[i];
numsMap.put(value,i);
Integer index = numsMap.get(target - value);
if(index != null && index != i) {
res[0] = index;
res[1] = i;
break;
}
}
return res;
}
public static void main(String[] args) {
int[] nums = new int[]{3,2,4};
int target = 6;
int[] res = twoSum2(nums,target);
System.out.println();
}
}