題目描述
給定一個整數(shù)數(shù)組 nums
和一個整數(shù)目標(biāo)值 target
,請你在該數(shù)組中找出 和為目標(biāo)值 target
的那 兩個 整數(shù),并返回它們的數(shù)組下標(biāo)肮之。
你可以假設(shè)每種輸入只會對應(yīng)一個答案压恒。但是魁袜,數(shù)組中同一個元素在答案里不能重復(fù)出現(xiàn)觉渴。
你可以按任意順序返回答案。
示例 1:
輸入:nums = [2,7,11,15], target = 9
輸出:[0,1]
解釋:因為 nums[0] + nums[1] == 9 包归,返回 [0, 1] 。
示例 2:
輸入:nums = [3,2,4], target = 6
輸出:[1,2]
示例 3:
輸入:nums = [3,3], target = 6
輸出:[0,1]
提示:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
- 只會存在一個有效答案
解題思路
本題目需要找到兩個數(shù)之和等于目標(biāo)值,因此很容易相當(dāng)構(gòu)造一個映射關(guān)系铅歼,由值到下標(biāo)的映射關(guān)系公壤。 當(dāng)遍歷至num值時换可,只用判斷num值是否存在于Map映射中,存在構(gòu)造結(jié)果即可厦幅!
代碼:
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res=new int[2];
Map<Integer,Integer> map=new HashMap<>();
for(int index=0;index<nums.length;index++){
int num=nums[index];
if(map.containsKey(target-num)){
res[1]=index;
res[0]=map.get(target-num);
break;
}
map.put(num,index);
}
return res;
}
}
運行效果:
image.png