在两个数组中查找最接近的数字
Finding closest numbers within two arrays
我必须在两个数组中找到最接近的数字并显示它们的差异。我用了一个循环,但是太花时间了。你知道有什么方法能让这个算法更快吗?
#include <cmath>
#include <cstdio>
using namespace std;
long long int red, yellow, minimum = 1000000000, difference = 0;
long long int TC[100001], ZT[100001];
int main()
{
scanf("%d", &red);
for (int y = 0; y < red; ++y)
{
scanf("%d", &TC[y]);
}
scanf("%d", &yellow);
for (int yy = 0; yy < yellow; ++yy)
{
scanf("%d", &ZT[yy]);
}
for (int yyy = 0; yyy < red; ++yyy)
{
for (int i = 0; i < yellow; ++i)
{
difference = abs(TC[yyy] - ZT[i]);
if (difference == 0)
{
minimum = 0;
break;
}
else if (difference < minimum)
minimum = difference;
}
}
printf("%d n", minimum);
}
应该是0 (nlgn):
sort two lists
let i = 0, j = 0, minval = abs(list1[0] - list2[0])
as long as both lists have more items:
minval = min(minval, abs(list1[i] - list2[j])
if abs(list1[i + 1] - list2[j]) < abs(list1[i] - list2[j + 1])
increment i
else increment j
如果您对它们进行排序,您可以优化算法以更快地运行。当您的两个数组都排序后,您可以逐一检查并比较它们,而不是使用当前的算法。因为您将跳过其中一些,因为您知道它们是排序的。
顺便说一下,因为你从用户那里得到数字,我建议你把数字排序。每次用户输入一个数字,把这个数字放在一个位置,在它后面的数字比它大,在它前面的数字比它小。要做到这一点,也许使用链表是更好的主意(或更容易)。
相关文章:
- 查找最接近的大于当前数字的数字的索引
- 在二维数组中查找最小值和最大值?
- C++如何在向量中查找最常见的元素
- 必须首先打印向量 v1 中最接近整数 x 的数字<int>
- 为什么使用数组元素查找最大数字的程序不起作用?
- 查找索引的最接近的真实值
- 查找最短路径算法
- 在结构向量中查找最接近的值
- 查找整数数组中最接近的数字
- 使用非线性级数查找最接近的值
- 查找记录等于或最接近使用向量C 的平均值
- 从均匀网格中查找最接近的数字
- 查找从列表到一个参考列表的最接近点
- 在数组中查找一个变量,哪个和最接近目标和
- 在std::映射中查找最接近或精确的关键字
- 使用数组查找最接近的数字C++,浮点
- 查找数组中与另一个给定数字最接近的数字
- 在两个数组中查找最接近的数字
- 在c++中查找小于特定整数值的最接近的浮点值
- C++11:`错误:代码中')'标记之前应有主表达式',用于行扫描以查找最接近的对