1 Two Sum

Topic Address: 1. Two Sum

Referring to a third solution which

I had a doubt: Why take complementas key?
General key-value pairs, then complementit should be value, and iis the keyson.

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

But if we look inside the key and value exchange, what will happen?

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

Here Insert Picture Description
Here Insert Picture Description
error! Because the if(map.containsKey(i))inside iis 0,1,2, we have to compare that num[]number inside (Figure: To compare that 1,3,11,8) instead i.

So we want to complementbe askey

Published 93 original articles · won praise 31 · views 30000 +

Guess you like

Origin blog.csdn.net/weixin_43866567/article/details/104869699