繁体   English   中英

Java-Leetcode两次和Hashmap解决方案

[英]Java - Leetcode Two Sum Hashmap Solution

我是Java的新手,我刚开始做Leetcode-两个和。 我发现除了蛮力解决方案之外,常见的解决方案是使用Hashmap。 但是我还是不明白。 例如,这符合我的逻辑:

public int[] twoSum(int[] nums, int target) {
    HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
    int[] res = new int[2];
    for (int i = 0; i < nums.length; ++i) {
        m.put(nums[i], i);
    }
    for (int i = 0; i < nums.length; ++i) {
        int t = target - nums[i];
        if (m.containsKey(t) && m.get(t) != i) {
            res[0] = i;
            res[1] = m.get(t);
            break;
        }
    }
    return res;
}

第一个for循环将数字放入Hashmap,然后使用第二个for循环检查是否可以找到等于target number - nums[i] 但是,我看到许多公认的解决方案将这两个for循环结合在一起,例如以下示例:

public int[] twoSum(int[] nums, int target) {
    HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
    int[] res = new int[2];
    for (int i = 0; i < nums.length; ++i) {
        if (m.containsKey(target - nums[i])) {
            res[0] = i;
            res[1] = m.get(target - nums[i]);
            break;
        }
        m.put(nums[i], i);
    }
    return res;
}

按照我的逻辑,第二个解决方案像这样运行for循环:

//[2,7,11,15]
when i=0, m.put(nums[0],2)
when i=1, m.put(nums[1],7)
when i=2, m.put(nums[2],11)
when i=3, m.put(nums[3],15)

并且因为i < nums.length所以当i = 4时,代码将跳转以return res 它不会再次运行for循环。 但是据我所知,我看到有人说第二种解决方案将遍历数组,并将索引和值存储到Hashmap中,然后再次进行遍历。 在我的想象中,只有一个for循环,他们如何才能使用唯一的for循环再次进行迭代?

不会有任何第二次迭代。 在一次迭代中,如果找到一对,则循环将中断。

考虑一下:

//[2,7,11,15] and target = 13
when i=0, m.put(mums[0],2)
when i=1, m.put(mums[1],7)
when i=2, m.contains(13 - mums[2]) == true // since 13 - 11 = 2 is present at index 0
res[0] = 2
res[1] = 0
break;

因此,.....你是对的。 只有一次迭代。

不需要两个for循环,这可以在您发布的单个for循环中完成。从性能的角度来看,最好在for循环中仅迭代一次并在第一个匹配对为找到。 在最坏的情况下为O(n)。

    public static int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int num : nums) {
        int rem = target - num;
        if (map.containsKey(rem)) {
            return new int[] { num, rem };
        }
        map.put(num, num);
    } // for
    return null;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM