c++ - 查找两个数组中最接近的数字

标签 c++ algorithm difference

<分区>

我必须在两个数组中找到最接近的数字并显示它们的差异。我为此使用了一个循环,但它需要太多时间。您知道使该算法更快的方法吗?

#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);
}

最佳答案

这应该是 O(log n):

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++ - 查找两个数组中最接近的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24989772/

相关文章:

c++ - QDomDocument - 如何从 QString 创建?

c++ - HPUX 上的套接字未收到完整数据

c++ - 标准关于可变参数模板的措辞

java - 给定约束的 Java 中最大大小的子集

c++ - '-std=c++11' 对 C++/ObjC++ 有效,但对 C 无效

algorithm - 在数组中找到一个在线性时间内比任何其他数组大两倍的数字

algorithm - 在多个数组中查找最近的元素

python - 计算两个类实例之间的数值增量

agile - CMMI和敏捷有什么区别?

php/mysql - 比较 2 个表中的多个列并显示最大差异