15,744,010 members
See more:
I have 2 arrays of natural numbers and 1 integer lets call it 'd'.
I need to find 2 numbers from 2 different arrays lets say 'x' and 'y' that fulfills a condition x-y=d or y-x=d.

I need the most efficient way.

What I have tried:

C
```int i, j, flag = 1;
for (i = 0; i < size_a; i++)
for (j = 0; j < size_b; j++)
if (abs(a[i] - b[j]) == num)
return 1;
return 0;```

It works but its not that efficien, if you guys have any better idea I'll be glad to hear it.

Nick
Posted
Updated 14-Jan-18 22:38pm
v2
CPallini 15-Jan-18 2:46am
If the arrays are not ordered I see no way to improve that.

## Solution 1

CPallini is right, so ordering could improve the speed of your loop because your can stop the looping when the diff gets greater than num. Think about dropping some comparison if the numbers are smaller than num. Maybe only if alway greater than zero.

If you need to find the numbers you also must store them for output.

C++
```if (abs(a[i] - b[j]) == num)
{
result1 = a[i];//store in variable with greater scope
result2 = b[i];
return 1;
}```
What about multiple solutions in the array?

But speed isnt the primary problem on that simple task. Such "optimization" often leads to complex and bizarre code which results in strange bugs and problems.

So anything you missed to mention?