1 Two Sum

题目地址: 1. Two Sum

参照里面第三种解法

我产生了一个疑惑:为啥要把complement当成key?
一般键值对的话,complement应该是value,而i才是key才对。

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[] { map.get(complement), i };
        }
        map.put(nums[i], i);
    }
    throw new IllegalArgumentException("No two sum solution");
}

但是如果我们把里面key和value调换一下,会怎么样?

class Solution {
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(i)) {
            return new int[] { i , map.get(complement)};
        }
        map.put( i ,nums[i]);
    }
    throw new IllegalArgumentException("No two sum solution");
}
}

在这里插入图片描述
在这里插入图片描述
错误!因为在if(map.containsKey(i))里面的i是0,1,2,我们要比较的是num[]里面的数(如图:要比较的是1,3,11,8),而不是i

所以我们要将complement来当作key

发布了93 篇原创文章 · 获赞 31 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_43866567/article/details/104869699