重点是:
在形成哈希表的循环中,将nums[] 中的值存入key中,下标 i 存入value 中,这样可以在之后的循环中用get 取得存入value 中的下标。
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
完整代码如下:
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
int[] result = new int[2];
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int j = 0; j < nums.length; j++) {
int temp = target - nums[j];
if (map.containsKey(temp) && map.get(temp) != j) {
result[0] = j;
result[1] = map.get(temp);
}
}
return result;
}