1.两数之和
大约 1 分钟
1.两数之和
参考链接
个人尝试
第一次遍历先把所有元素放入 HashMap 中,第二次遍历再寻找是否有 两数之和 == target 的组合
其实可以只需一次遍历即可。
class Solution {
public int[] twoSum(int[] nums, int target) {
if (nums == null || nums.length == 0) return new int[0];
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i]) && map.get(target - nums[i]) != i) {
return new int[]{i, map.get(target - nums[i])};
}
}
return new int[0];
}
}
优秀题解
题解来源:代码随想录
//使用哈希表
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
if(nums == null || nums.length == 0){
return res;
}
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
int temp = target - nums[i]; // 遍历当前元素,并在map中寻找是否有匹配的key
if(map.containsKey(temp)){
res[1] = i;
res[0] = map.get(temp);
break;
}
map.put(nums[i], i); // 如果没找到匹配对,就把访问过的元素和下标加入到map中
}
return res;
}
采用 HashMap 存放已遍历过的元素,即可达成快速寻找数组中是否有 两数相加 == target 的组合,并且只需遍历一遍数组。