一、题目
给定一个整数
数组 nums 和一个目标值
target,请你在该数组中找出和为目标值
的那两个整数
,并返回他们的数组下标
。
注意:你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
二、实现
- 时间复杂度:
O(n)
- 空间复杂度:
O(n)
public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i]; //目标值 - 当前值 = 另一个值
if (map.containsKey(complement)) { //如果map中,已经存在key为另一个值,说明找到了
return new int[] { map.get(complement), i };
}
map.put(nums[i], i); //以元素为key,下标为value
}
throw new IllegalArgumentException("No two sum solution");
}