Find two elements in an array that sum to k [duplicate]
Possible Duplicate:
Given two arrays a and b .Find all pairs of elements (a1,b1) such that a1 belongs to Array A and b1 belongs to Array B whose sum a1+b1 = k .
Given : An unsorted array A
of integers
k
Output : All the two element set with sum of elements in each set equal to k
in O(n).
Example:
A = {3,4,5,1,4,2}
Input : 6
Output :{3,3}, {5,1}, {4,2}
Note : I know an O(n logn) solution but that would 开发者_StackOverflowrequire to have the array sorted. Is there any way by which this problem can be solved in O(n). An non-trivial C++ data structure can be used i.e there's no bound on space
Make a constant-time lookup table (hash) so you can see if a particular integer is included in your array (O(n)). Then, for each element in the array, see if k-A[i]
is included. This takes constant time for each element, so a total of O(n) time. This assumes the elements are distinct; it is not difficult to make it work with repeating elements.
Just a simple algorithm off the top of my head:
- Create a bitfield that represents the numbers from 0 to k, labeled B
- For each number i in A
- Set B[i]
- If B[k-i] is set, add (i, k-i) to the output
Now as people have raised, if you need to have two instances of the number 3 to output (3, 3) then you just switch the order of the last two statements in the above algorithm.
Also I'm sure that there's a name for this algorithm, or at least some better one, so if anyone knows I'd be appreciative of a comment.
http://codepad.org/QR9ptUwR
This will print all pairs. The algorithm is same as told by @bdares above.
I have used stl maps as we dont have hash tables in STL.
One can reduce the,
Element Uniqueness bit,
to this. No O(n).
There are k pairs of integers that sum to k: {0,k}, {1,k-1}, ... etc. Create an array B of size k+1 where elements are boolean. For each element e of the array A, if e <= k && B[e] == false, set B[e] = true and if B[k-e] == true, emit the pair {e,k-e}. Needs to be extended slightly for negative integers.
精彩评论