1.4.15 twoSumFaster may have some mistakes
davisrain opened this issue · 2 comments
davisrain commented
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;
}
reneargento commented
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?
davisrain commented
sorry,it's my fault. Your implementation is indeed correct.