【发布时间】:2020-06-13 05:44:09
【问题描述】:
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[]{i, map.get(complement)};
}
}
throw new IllegalArgumentException("No two sum solution");
}
我正在尝试使用 Hashtable 方法在 leetcode 中进行“二和”。但是,当我运行上面的代码时,它最终会引发异常。当我将map.put(nums[i], i)这一行放到for循环的末尾,并删除“if”子句中的第二个条件
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[]{i, map.get(complement)};
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
此代码运行正确。这两个版本的代码有什么区别?
【问题讨论】: