当前位置: 首页 > 知识库问答 >
问题:

为什么在使用HashMap求解Leetcode Two Sum时,如果在检查解决方案之前使用do Map.Put会失败?

翟鹏
2023-03-14

对于经典的Leetcode二和问题:给定一个数组,返回两个数的索引,使它们相加为一个特定的目标。

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

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

共有1个答案

汪才英
2023-03-14

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

假设对某些ij目标==arr[i]+arr[j],使得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)
 类似资料:
  • 我是这里的初学者,这个代码在理论上应该是可行的,为你们这些很棒的家伙们帮我干杯! 13195的质因数是5、7、13、29。 600851475143的最大质因数是什么? 欧拉问题3

  • 下面是一个我试图从中获取数据的示例网页。http://www.makospearguns.com/product-p/mcffgb.htm xpath取自chrome开发工具,firefox中的firepath也能找到它,但使用lxml它只返回一个空的“文本”列表。 使用 显示数据在那里,但xpath似乎无法找到它。我有什么遗漏吗?我尝试过的大多数其他站点使用lxml和chromedev工具中的x

  • 我对Docker很陌生,尝试用普通html构建Docker图像,但我有一条错误消息,说用前端dockerfile解决问题失败。v0:无法读取dockerfile:open/var/lib/docker/tmp/buildkit-mount602954594/dockerfile:没有这样的文件或目录 我的文件夹目录如下 在Dockerfile里面,我有 我做了我的命令docker构建。在目录C:\

  • 对于python我是新手,我正在做leetcode问题94,二叉树顺序遍历。给定二叉树的根,返回对其节点值的inorder遍历。 但我还是不明白它为什么有用。在之后,在递归过程中,res变量不会被重新分配给[]吗?或者res变量在不同的递归中应该是不同的变量吗?

  • 在解决问题的过程中,我实际上面临着一个问题。我的问题是一个线性规划问题,具有食物饮食优化和成本最小化。因为这个问题和这个类似(https://ibmdecisionoptimization.github.io/docplex-doc/mp/diet.html),我已经在Python中安装了docplex来解决这个问题,它可以正常工作!问题是我需要获得所有可行的解决方案并将其输出。但是IBM的例子只

  • Values.java AmountDetail.java 当我在postman if子句中点击API时,它工作正常,但如果我想检查else,它会给出错误。我觉得铸造是这里的问题,但我不知道如何返回else块的值。