在两个数组中查找最接近的数字

Finding closest numbers within two arrays

本文关键字:查找 最接近 数字 数组 两个      更新时间:2023-10-16

我必须在两个数组中找到最接近的数字并显示它们的差异。我用了一个循环,但是太花时间了。你知道有什么方法能让这个算法更快吗?

#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

如果您对它们进行排序,您可以优化算法以更快地运行。当您的两个数组都排序后,您可以逐一检查并比较它们,而不是使用当前的算法。因为您将跳过其中一些,因为您知道它们是排序的。

顺便说一下,因为你从用户那里得到数字,我建议你把数字排序。每次用户输入一个数字,把这个数字放在一个位置,在它后面的数字比它大,在它前面的数字比它小。要做到这一点,也许使用链表是更好的主意(或更容易)。