题目
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案,并且你不能使用两次相同的元素。
你可以按任意顺序返回答案。
思路
题目需要找出和为 target 的两个数的下标
使用哈希表存储 值和下标, 如果 target - num 在 map 中则返回
代码
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int num = nums[i];
int sub = target - num;
if (map.containsKey(sub)) {
res[0] = map.get(sub);
res[1] = i;
}
map.put(num, i);
}
return res;
}
}