(The question in its current form is a bit confusing - my answer suggests that the question is to find two numbers in the array that sum with the given value)
Since this array is unsorted, I assume that we are not allowed to sort the array (i.e. this array order cannot be changed).
The simplest IMHO solution is to iterate over each x number and verify that Ix occurs anywhere in arrays. This is essentially what your O (n ^ 2) solution makes.
This can be reduced to O (n) or O (nlogn), speeding up the search using some quick data structure. Basically, when we iterate over an array, we ask if there is an Ix in the set.
Code (in Python):
l=[1,2,3,4,5,6,7,8,9] seen=set() I=11 for item in l: if I-item in seen: print "(%d,%d)"%(item,I-item) seen.add(item)
The complexity of the solution depends on the complexity of inserting / searching the set data structure that you are using. The hash table-based implementation has O (1) complexity, so it gives you the O (n) algorithm, and the set tree leads to the O (nlogn) algorithm.
Edit:
The equivalent data structure for Python set will be stl::set in C ++ and TreeSet / HashSet in Java. The string Ix in seen converted to seen.contains(Ix) in Java and seen.find(Ix)==seen.end() in C ++.
source share