Click here to Skip to main content
14,428,023 members
Rate this:
Please Sign up or sign in to vote.
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:

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.

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

1 solution

Rate this:
Please Sign up or sign in to vote.

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.

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?
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100