Design an algorithm to find all pairs of integers within an array which sum to a specified value.
I have tried this problem using a hash
You don't even need to store all the elements in hashmap, and then scan. You can scan during the first iteration itself.
void foo(int[] A, int sum) {
HashSet set = new HashSet();
for (int e : A) {
if (set.contains(sum-e)) {
System.out.println(e + "," + (sum-e));
// deal with the duplicated case
set.remove(sum-e);
} else {
set.add(e);
}
}
}