给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
链接:https://leetcode-cn.com/problems/two-sum
class TwoSum{
//方法1:利用Map
public int[] twoSum1(int[] nums, int target) {
int[] result = new int[2];
result[0] = -1;
result[1] = -1;
Map<Integer,Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i ++){
//如果map里有target-nums[i],就返回,否则把nums[i]放到map里
if (map.get(target - nums[i]) != null){
result[0] = i;
result[1] = map.get(target - nums[i]);
}else{
map.put(nums[i],i);
}
}
return result;
}
//方法2:两重for循环查找,对于nums[i],找数组中是否有target-nums[i],如果i=j就跳过,找到就返回
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
result[0] = -1;
result[1] = -1;
a:for(int i = 0; i < nums.length; i ++){
int minus = target - nums[i];
for (int j = 0; j < nums.length; j++){
if (i == j){
continue;
}
if (minus == nums[j]){
result[0] = i;
result[1] = j;
break a;
}
}
}
return result;
}
}