java - 为什么在用hashmap解Leetcode Two Sum的时候先查解再做map.put会失败?

标签 java

对于经典的 Leetcode TwoSum 问题: 给定一个整数数组,返回两个数字的索引,使它们加起来达到特定目标。

您可以假设每个输入只有一个解决方案,并且您可能不会两次使用相同的元素。

例子:

给定 nums = [2, 7, 11, 15],target = 9,因为 nums[0] + nums[1] = 2 + 7 = 9,返回 [0, 1]。

试过下面的代码,它会通过测试用例,但提交失败。

public class Solution {
    public int[] twoSum (int[] arr, int target) {
        if (arr == null || arr.length < 1) {
            throw new IllegalArgumentException ("array given is null or 
length less than 1, no two sum solutions"); 
        }
        Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 
        for (int i = 0; i < arr.length; i++) {
            map.put (arr[i], i);
            int component = target -arr[i]; 
            if (map.containsKey(component) && map.get(component) != i) {
                return new int[] {i, map.get(component)};
            }
        }   
        throw new IllegalArgumentException (" no two sum solution found 
"); 
    }
}

虽然如果我在解决方案检查后移动 map.put 如下,将通过,但无法弄清楚为什么?

public class Solution {
    public int[] twoSum (int[] arr, int target) {
        if (arr == null || arr.length < 1) {
            throw new IllegalArgumentException ("array given is null or 
length less than 1, no two sum solutions"); 
        }
        Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 
        for (int i = 0; i < arr.length; i++) {

            int component = target -arr[i]; 
            if (map.containsKey(component) && map.get(component) != i) {
                return new int[] {i, map.get(component)};
            }
            map.put (arr[i], i);
        }   
        throw new IllegalArgumentException (" no two sum solution found 
"); 
    }
}

最佳答案

如果数组包含重复项,并且 target 是两个相等数组元素的总和,您的第一个代码段将失败。

假设 target == arr[i] + arr[j] 对于一些 ij 使得 i<jarr[i]==arr[j]。在这种情况下,您将首先放入 map.put (arr[i], i),然后用 map.put (arr[j], j) 覆盖它。结果,map.containsKey(component) 将为 truemap.get(component) != i 将为 false ,你将无法返回索引对 ij

因此,您应该在检查条件后才将当前元素添加到Map

例如,以下输入将在第一个解决方案中失败并在第二个解决方案中成功:

twoSum(new int[] {4,5,7,5},10)

关于java - 为什么在用hashmap解Leetcode Two Sum的时候先查解再做map.put会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56747839/

相关文章:

java - java中非静态方法如何访问静态成员?

java - 如何在不同进程中使用 LocalBroadcastManager 在 Activity 和服务之间进行通信

java - Java 代码如何检查浮点寄存器的数量?

java - 有人可以向我解释一下这个递归背后的逻辑吗

java - 使用 Cairo 渲染到 SWING 表面(例如 JPanel)

javascript - socket.io 客户端连接到服务器但不通信

java - Eclipse 启动错误的 .Class 文件

java - Java 中如何判断一个字符串是否等于某个数字范围?

java - Gradle:我可以编译依赖于自身输出的代码吗?

java - session 无效后,如何强制Jetty使用BASIC身份验证要求凭证?