//Write a program that, given an array A[] of n numbers and another number x, determines whether or not there exist two elements in S whose sum is exactly x.
public class PairsInAnArray {
boolean findPair(List<Integer> list, int x) {
int count =0;
//{1, 4, 45, 6, 10, -8} and sum to find be 16
HashSet visited = new HashSet();
for (int i = 0; i < list.size(); i++) {
int toBePairedUp = x - list.get(i);
if(visited.contains(toBePairedUp)) {
return true;
}
visited.add(list.get(i));
}
return false;
}
}
And here is the test to verify
public class PairsInAnArrayTest {
@Test
public void findPair() {
final PairsInAnArray pairsInAnArray = new PairsInAnArray();
Assert.assertFalse(pairsInAnArray.findPair(Arrays.asList(1, 3, 5, 8, 4), 14));
Assert.assertTrue(pairsInAnArray.findPair(Arrays.asList(7, 6, 5, 8, 4), 14));
}
}