0
public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        map.put(nums[i], i);
        int complement = target - nums[i];
        if (map.containsKey(complement) && map.get(complement) != i) {
            return new int[]{i, map.get(complement)};
        }
    }
    throw new IllegalArgumentException("No two sum solution");
}

I'm trying to do the "two sum" in leetcode using a Hashtable method. However, when I run the code above, it ends up throws an exception. When I put the line map.put(nums[i], i) to the end of the for loop, and delete the second condition in the "if" clause

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

This code runs correctly. What's the difference between these two versions of code?

xunmiw
  • 21
  • 3

2 Answers2

0

You first have to check if a complement exists before inserting.

Example:

[2, 0, 2] and let the target be 4.

In the first case, when you reach index 2, the map would have {2=0, 0=1}. When you see the last element, you are first inserting into the map. The map now becomes

{2=2, 0=1}

The complement's index is now is equal to the current index (2) and hence it fails.

However, in the second code snippet, you would find that a complement exists (at index 0).

Thiyagu
  • 17,362
  • 5
  • 42
  • 79
0

The first code can not handle the test case in which the target is composed by two elements which are equal. Consider this test case:

nums=[1,2,2] target=4.

the second code is correct. While the first one is not:

when handling the last element(2), firstly the existing <2,1> entry in the map is replaced by <2,2> by the map.put(nums[i], i);, then the if clause will be fasle(map.get(complement) will equals to i, which is 2), which make the code throw an Exception.


To avoid the code fails in some test cases, before coding, we should consider different test cases firstly, which is called TDD(Test Driven Development). Practice more will give you some ideas on how to figure our all possible test cases.

ZhaoGang
  • 4,491
  • 1
  • 27
  • 39