难度: easy
题目描述:给定一个数组和一个目标值target,求出两数之和等于target的这两个数的index
例子:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
思路: 哈希表
解法:one-pass 哈希
public int[] twoSum(int[] nums, int target) {
//先声明一个int,int型哈希map
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
//遍历到数组中每一个数字时,都计算target减当前数字的差
int complement = target - nums[i];
//如果说哈希map中有这个差值的话,就说明我们找到解了
if (map.containsKey(complement)) {
//返回当前遍历到的数的index和差值作为key的对应的hash值,就是下一句中放入的数字和index
return new int[] { map.get(complement), i };
}
//遍历时把数字和index放入哈希map中
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}