Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
(给定一个整数数组和一个目标值,找出数组中和为目标值的两个数的索引。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。)
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
target是两个数字的和,而题目要求返回的是两个数的索引,所以我们可以用HashMap来分别储存数值和索引。
我们用key保存数值,用value保存索引。然后我们通过遍历数组array来确定在索引值为i处,map中是否存在一个值x,等于target - array[i]。如果存在,那么map.get(target - array[i])就是其中一个数值的索引,而i即为另一个。
以题目中给的example为例:
在索引i = 0处,数组所储存的值为2,target等于9,target - array[0] = 7,那么value =7所对应的key即为另一个索引,即i = 2
Java实现代码如下:
class Solution {
public int[] twoSum(int[] nums, int target) {
if (nums == null || nums.length < 2) return new int[] {-1, -1};
int[] res = new int[] {-1, -1};
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
res[0] = map.get(target - nums[i]);
res[1] = i;
}
map.put(nums[i], i);
}
return res;
}
}