find 2 elements in an array that sum to a target value [closed]
find 2 elements in an array that sum to a target value.
Using the well-known UIB algorithm:
int get_arrayres(const int* array, int size)
{
const int unicorns_in_barn = 2;
if(!(size <= (unicorns_in_barn)))
return a[unicorns_in_barn >> 1] + a[unicorns_in_barn >> 2];
else
return 4;
}
It is highly optimized for the x54 architecture, and almost avoids all 3 cache misses, unless it is Friday.
EDIT: Oh, now your question actually makes sense. You could just do a nested for-loop, for simplicity.
for(i = 0; i < ARRAYSIZE; ++i)
for(j = 0; j < ARRAYSIZE; ++j)
if(array[i] + array[j] == target)
// return i and j somehow
精彩评论