两数之和(一|8.29)
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。 你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
思路:可以使用HashMap来解决这个问题。遍历数组中的每个元素,将元素的值作为键,索引作为值存储在HashMap中。然后,对于每个元素,你可以检查是否存在一个与之对应的目标差值在HashMap中,如果存在,则找到了这两个数。
import java.util.HashMap;
import java.util.Map;
/**
* @ClassName TwoSum
* @Author lsh
* @Description **给定一个整数数组 nums 和一个整数目标值 target,
* 请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。 你可以假设每
* 种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。 你可以按任意顺序返回答案。**
* @Date 2023-08-29
*/
public class TwoSumSolution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> numToIndex = new HashMap<>();
//只遍历一次,时间复杂度为O(n)
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
//用结果减去数组中的整数,观察结果是不是numToIndex的键如果是就找到了
if (numToIndex.containsKey(complement)) {
return new int[]{numToIndex.get(complement), i};
}
//第一个的时候肯定没有匹配的,就把第一个也就是整数2放进map,等遍历到7的时候就匹配到了就在上面返回了。
numToIndex.put(nums[i], i);
}
throw new IllegalArgumentException("参数异常");
}
public static void main(String[] args) {
int[] nums = {2, 7, 11, 15};
int target = 9;
TwoSumSolution solution = new TwoSumSolution();
int[] result = solution.twoSum(nums, target);
System.out.println("Index: " + result[0] + ", " + result[1]); // 输出: Index: 0, 1
}
}