(); for (int i = 0; i -6ren">
gpt4 book ai didi

java - 如何使用哈希表解决leetcode中的 "two sum"问题?

转载 作者:行者123 更新时间:2023-12-01 18:11:28 25 4
gpt4 key购买 nike

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");
}

我正在尝试使用哈希表方法在 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");
}

这段代码运行正确。这两个版本的代码有什么区别?

最佳答案

在插入之前,您首先必须检查补码是否存在。

示例:

[2, 0, 2] 并让目标为 4。

在第一种情况下,当您到达索引 2 时, map 上将显示 {2=0, 0=1}。当您看到最后一个元素时,您首先将其插入到 map 中。 map 现在变成了

{2=2, 0=1}

补集的索引现在等于当前索引 (2),因此失败。

但是,在第二个代码片段中,您会发现存在补码(位于索引 0 处)。

关于java - 如何使用哈希表解决leetcode中的 "two sum"问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60463263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com