Arrays 数组中两个数字之间的最小绝对差

Arrays 数组中两个数字之间的最小绝对差,arrays,algorithm,Arrays,Algorithm,给定两个数组,A和B,我想从A中找出一个数,从B中找出一个数,这样两个数之间的绝对差最小 乙二醇 Ans:2,4 as Math.abs(2-4)=2对两个数组排序,然后并行迭代:对于A中的每个项目,通过线性搜索搜索B中最近的项目。在B中开始线性搜索,在此处停止搜索A的上一项。始终记住迄今为止发现的最小距离 排序的时间复杂度为O(m log m+n log n),最终搜索的时间复杂度为O(m+n),其中m和n分别是A和B的长度。检查此项,可能会给您一个想法,以便您根据需要调整它: #define

给定两个数组,A和B,我想从A中找出一个数,从B中找出一个数,这样两个数之间的绝对差最小

乙二醇


Ans:2,4 as Math.abs(2-4)=2对两个数组排序,然后并行迭代:对于
A
中的每个项目,通过线性搜索搜索
B
中最近的项目。在
B
中开始线性搜索,在此处停止搜索
A
的上一项。始终记住迄今为止发现的最小距离


排序的时间复杂度为O(m log m+n log n),最终搜索的时间复杂度为O(m+n),其中m和n分别是
A
B
的长度。检查此项,可能会给您一个想法,以便您根据需要调整它:

#define TOP 2147483647
#define true 1
#define false 0


/* finds the minimum (absolute value) of vector vec */

void Vector_Min_Not_0(vector *vec, int *min, int *index)
{
  int m, size, i, ind, aux;

  size = vec->size;
  m = TOP;
  ind = -1;
  for (i = 0; i < size; i++)
    if (vec->p[i] != 0)
      if (m > (aux = abs(vec->p[i]))) {
    ind = i;
    m = aux;
      }
  if (ind == -1)
    *min = 1;
  else
    *min = m;
  *index = ind;
} 
可以在O(nlogm+mlogm)=O(nlogm)中完成:
(m是数组的最小长度)
假设B是较小的数组

sort array B
minimum =  | A[0]-B[0] | 
for each a in A:
binary search for a in B - return the closest numbers let the numbers be b1,b2 (*)
if min{|b1-a|,|b2-a|} is smaller then the previous minimum - store it as the new minimum

(*)当您最接近该号码时,二进制搜索将停止(如果该号码存在,则会找到该号码)

首先检查较小的(A或B)将确保更好的性能。-

我假设数组中的数字将是浮点数。在Ruby中:

def smaller_abs(array1, array2)
  array1.product(array2).each_with_index do |ar,i|
      if i==0
        dif = (ar[0]-ar[1]).abs
        pair = ar
        next
      end
      pair = (ar[0]-ar[1]).abs > dif ? pair : ar
  end
  pair
end
我不是一个算法大师,但这一定行得通(还没有签出)。希望我能帮忙

  • 对两个数组进行排序
  • 使用一些标记将这两个数字组合起来以区分它们。 e、 g A=1 9 2 B=5 4 6
  • 排序后:

    A=1 2 9 B=4 5 6

    组合阵列:C=1a 2a 4b 5b 6b 9a

    现在做一个线性搜索,找出不同标签的连续术语之间的差异。
    答案:2a 4b。

    什么编程语言?如果不重要,请使用代码golf。假设数组是(10,11,14)(4,6,8),在这种情况下,您的不是将是一个O(n^2)算法。如果数组已经排序,您可能希望使用二进制搜索。@算法师:不,搜索将是O(m+n),因为您总是选择上次停止的位置。您给出的示例甚至允许提前退出,因为您将为
    A
    中的第一项消耗所有
    B
    ,因此您不必再进一步查找。@Phimueme:我认为线性搜索在这里已经足够了--搜索部分的复杂性只有O(m+n),而二进制搜索则是O(n log m)。只要与当前考虑的
    A
    项的距离再次增加,您就可以停止搜索
    B
    sort array B
    minimum =  | A[0]-B[0] | 
    for each a in A:
    binary search for a in B - return the closest numbers let the numbers be b1,b2 (*)
    if min{|b1-a|,|b2-a|} is smaller then the previous minimum - store it as the new minimum
    
    def smaller_abs(array1, array2)
      array1.product(array2).each_with_index do |ar,i|
          if i==0
            dif = (ar[0]-ar[1]).abs
            pair = ar
            next
          end
          pair = (ar[0]-ar[1]).abs > dif ? pair : ar
      end
      pair
    end