Use in-place radial sorting and the first OP solution with two iterators approaching each other.
If the numbers in the array are not some types of numbers with several points and are, for example, 32-bit integers, you can sort them by 2 * 32 passes, using almost no additional space (1 bit per pass). Or 2 * 8 passes and 16 integer counters (4 bits per pass).
Details for a solution with two iterators:
First, the iterator first points to the first element of the sorted array and advances. The second iterator initially points to the last element of the array and moves backward.
If the sum of the elements referenced by the iterators is less than the required value, advance the first iterator. If it is greater than the desired value, advance the second iterator. If it is equal to the required value, success.
Only one pass is required, so the time complexity is O (n). The complexity of the space is O (1). If radix sorting is used, the complexity of the whole algorithm is the same.
If you are interested in related problems (with a sum of more than two numbers), see "Sum of a subset with a fixed size of a subset" and "Search for three elements in an array whose sum is closest to a given number . "
Evgeny Kluev Mar 11 2018-12-12T00: 00Z
source share