题目描述
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例1
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
思路一:线性查找
代码如下:
public int[] twoSum(int[] nums, int target) {
if (nums == null || nums.length == 0) return new int[0];
for (int i = 0; i < nums.length; i++) {
int x = nums[i];//先定义好一个值
for (int j = i + 1; j < nums.length; j++) {//从定义好的值的下一位开始查找
if (nums[j] == target - x) {//若查找到符合条件的值
return new int[]{i, j};//则返回找到值的下标
}
}
}
return new int[0];//否则返回零
}
思路二:哈希查找
将整数数组nums中的数据都保存到一个哈希map中,(哈希map不仅可以存储数值,还可以存储下标,为返回条件提供了便利)
然后遍历整个哈希map,先定义好一个x,我们只要在哈希map中查找到target-x的值,返回该值的下标即可。(这里面注意有可能x的下标和target-x值的下标相同,因此在这儿我们需要做一个if判断即可,具体代码如下)
代码如下:
class Solution {
public int[] twoSum(int[] nums, int target) {
if(nums == null || nums.length == 0){
return new int[0];
}
//数据预处理,构建一个哈希map,不仅可以存储数组的值,还可以存储数组值的下标
HashMap<Integer,Integer> map = new HashMap<>();
for(int i = 0;i<nums.length;i++){//遍历数组,将数组的值以及下标存到哈希map中
map.put(nums[i],i);
}
for(int i = 0;i < nums.length; i++){
int x = nums[i];
if(map.containsKey(target-x)){//如果map中存在target - x
int index = map.get(target - x);//获取target - x 的下标
if(i != index){//题目中要求同一元素不能重复出现,所以要满足i和index不相同
return new int[]{i,index};//才能返回两数的下标
}
}
}
return new int[0];//否则返回为空
}
}