本文已参与「新人创作礼」活动,一起开启掘金创作之路 力扣题目链接
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
一上手我就是个暴力破解
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
//处理初始数组
for (int i = 0; i < nums.length; i++) {
//因为是两个数,temp为应该出现的结果
int temp = target - nums[i];
for (int j = 0; j < nums.length; j++) {
//不能一个数用两次
if (i == j) {
continue;
}
if (temp == nums[j]) {
result[0] = i;
result[1] = j;
return result;
}
}
}
return null;
}
显然。。不应该这么做。换个思路,用哈希表的思想。
public static int[] twoSum2(int[] nums, int target) {
int[] result = new int[2];
HashMap<Integer, Integer> map = new HashMap<>();
//处理初始数组
for (int i = 0; i < nums.length; i++) {
int temp = target - nums[i];
//根据键查找,需要的值是否存在
if (map.get(nums[i]) != null) {
for (int j = 0; j < nums.length; j++) {
if (temp == nums[j] && i != j) {
result[0] = i;
result[1] = j;
return result;
}
}
}
//把下一次需要的值作为键
map.put(temp, nums[i]);
}
return null;
}