题目如下
给定一个整数数组 nums 和一个整数目标值 target,
请你在该数组中找出 和为目标值 target 的那 两个 整数,
并返回它们的数组下标
第一种解法,暴力枚举
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] ints = new int[2];
// 双重for 循环
for(int i=0;i<nums.length;i++)
for(int j=0;j<nums.length;j++)
if(nums[i] + nums[j] == target && i != j) {
ints[0] = i;
ints[1] = j;
break;
}
return ints;
}
}
第二种使用hash
class Solution {
public int[] twoSum(int[] nums, int target) {
// 创建一个hash
HashMap<Integer, Integer> map = new HashMap<Integer,Integer>();
// 进行循环
for(int i=0;i<nums.length;i++){
// 若是map不存在该target - nums[i] 元素的键,就把该 nums[i],索引放入hash 中
if(map.containsKey(target - nums[i])) {
// 若存在,则直接返回,target - nums[i] 对应的索引值,以及当前索引值
return new int[]{map.get(target - nums[i]), i};
}
map.put(nums[i],i);
}
// 若没有找到,则返回空数组
return new int[0];
}
}
总结:
在遇到需要返回键值的情况下,可以采用 hash 进行构建 本题可以将值所对应的索引存储下来,方便后面的判断