給定一個(gè)整數(shù)數(shù)組 nums 和一個(gè)整數(shù)目標(biāo)值 target侣背,請你在該數(shù)組中找出 和為目標(biāo)值 target 的那 兩個(gè) 整數(shù),并返回它們的數(shù)組下標(biāo)慨默。
輸入:nums = [2,7,11,15], target = 9
輸出:[0,1]
解釋:因?yàn)?nums[0] + nums[1] == 9 贩耐,返回 [0, 1] 。
語法
JAVA實(shí)現(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] , 另一個(gè)是target - nums[I]
int another = target - nums[I];
// 如果another也在哈希表中厦取,且another的下標(biāo)不是nums[i]潮太,說明找到兩數(shù)之中的另外一個(gè)數(shù)
if (map.containsKey(another) && i != map.get(another)) {
// map.get(another) 獲取到另外一個(gè)數(shù)的下標(biāo)
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]