給定一個整數(shù)數(shù)組 nums 和一個整數(shù)目標值 target,請你在該數(shù)組中找出 和為目標值 target 的那 兩個 整數(shù),并返回它們的數(shù)組下標。
輸入:nums = [2,7,11,15], target = 9
輸出:[0,1]
解釋:因為 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
語法

JAVA實現(xiàn)
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++) {
// 兩數(shù)之和固定是nums[i] , 另一個是target - nums[I]
int another = target - nums[I];
// 如果another也在哈希表中,且another的下標不是nums[i],說明找到兩數(shù)之中的另外一個數(shù)
if (map.containsKey(another) && i != map.get(another)) {
// map.get(another) 獲取到另外一個數(shù)的下標
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]