给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
语法
JAVA实现
class Solution {
public int[] twoSum(int[] nums, int target) {
if (nums == null) return null;
// 哈希表key是nums[i] values是 I
Map<Integer,Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
// 两数之和固定是nums[i] , 另一个是target - nums[I]
int another = target - nums[I];
// 如果another也在哈希表中,且another的下标不是nums[i],说明找到两数之中的另外一个数
if (map.containsKey(another) && i != map.get(another)) {
// map.get(another) 获取到另外一个数的下标
return new int[]{i, map.get(another)};
}
// 初始化哈希表
map.put(nums[i], i);
}
return null;
}
}
LeetCode
return new int[]{map.get(another),I};
[2,7,11,15] 9
返回[0,1]
return new int[]{i,map.get(another)};
[2,7,11,15] 9
返回[1,0]