找到两个数组中2个数字之间的距离 [英] Find distance between 2 numbers in two arrays

查看:281
本文介绍了找到两个数组中2个数字之间的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个自然数组和1个整数,我们称它为'd'。

我需要从2个不同的数组中找到2个数字,让我们说'x'和'y'表示满足条件xy = d或yx = d。



我需要最有效的方式。



我尝试过:



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

推荐答案

CPallini是对的,所以排序可以提高你的循环速度,因为你可以在diff时停止循环大于num。如果数字小于num,请考虑删除一些比较。也许只有当大于零时。



如果你需要找到这些数字,你也必须存储它们以便输出。



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?


这篇关于找到两个数组中2个数字之间的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆