![](https://i-blog.csdnimg.cn/blog_migrate/9d485325b61f32aefd4202bd81a54707.png)
public int[] twoSum (int[] nums, int target) {
// write code here
}
计算target-nums[i]是否存在于哈希表中,如果不存在,则以target-nums[i]为键,i为值存入哈希表。
代码如下:
public int[] twoSum (int[] nums, int target) {
int[] res = new
int[0]; //如果没有符合条件的两个数,则返回空数组
HashMap<Integer, Integer>hash = new HashMap();
for (int i = 0; i < nums.length; i++) {
int temp = target - nums[i];
if (!hash.containsKey(temp)) {
hash.put(nums[i], i);
}
else
return new int[] {hash.get(temp)+1,i+1};
}
return res;
}