You are given an array, and a number x. Determines whether or not there exist two elements in in the input array whose sum is exactly x, efficiently.
Anónimo
If the array is initially unsorted: -O(NlogN) runtime, no additional memory: Sort the array. For each element i, perform a binary search on the array for X-i. -O(N) runtime, O(N) additional memory: Stick all of the elements in a HashSet. For each element i, check whether X-i is present in the set. If the array is initially sorted: Create two pointers, one originally to the first entry in the array and the other to the last. At each step, check how the sum of the two entries currently being considered compares to X. If it's too small, increment the first pointer. If it's too big, decrement the second. If it's equal, we are done. This process will locate a pair summing to X, if such a pair exists. Otherwise, we will know that no such pair exists as soon as the pointers coincide.