reneargento/algorithms-sedgewick-wayne

1.4.15 twoSumFaster may have some mistakes

davisrain opened this issue · 2 comments

my code:

public static int twoSumFaster(int[] a) {

    Map<Integer, Integer> map = new HashMap<>();
    for (int key : a) {
        Integer num = map.getOrDefault(key, 0);
        map.put(key, num + 1);
    }

    int count = 0;
    for (Integer key : map.keySet()) {
        if (map.containsKey(-key)) {

            // this is the different part
            if (key == 0) {
                count += (map.get(key) - 1) * map.get(key);
            } else {
                count += map.get(-key) * map.get(key);
            }

        }
    }
    return count / 2;
}

Your code is correct, but it seems that my implementation is also correct. Do you know any input where my method would give a wrong result?

sorry,it's my fault. Your implementation is indeed correct.