Possible Duplicate:
checking if 2 numbers of array add up to I
My Problem is i have a given number no=10; assume and a Array A the i have to find those no who’s difference is the given no..
Ex:- A[5]-A[3]=10; then Print print(A[5]); Print(A[5])
I have a algorithm that do it in O(n^2) time but we need something better…
My intuition is may be do something after Shorting the Array….. But How.. because after shorting it also need two loop to check that condition….
I am little bit confused ……
Original answer – O(n log n)
How about:
xdo a binary search forx + noOverall cost: O(n log n)
Modification to the above, as per Steve Jessop’s comment:
This still requires a sort beforehand, which is O(n log n) though.
Best answer IMO (simple to implement and O(n))
EDIT: Or, of course, build a
HashSetto make the containment check even quicker (assuming that creating the set is amortized O(n) and lookups are O(1)):