获取阵列内元素的距离?

时间:2015-04-28 11:52:42

标签: ruby-on-rails algorithm time-complexity

我正在努力完成一项非常简单的任务,该任务有一系列非负整数,我需要返回最近的距离。

数组:arr = [8, 24, 3, 20, 1, 17]

解决方案:2arr[2]-arr[4]

Sor far,我只设法写了一个O(n ^ 2)解决方案,这显然不够好:

def smallest_distance(a)
  result = nil
  a.each_with_index do |item1, index1|
    a.each_with_index do |item2, index2|
      next if index1 == index2
      temp = (item1 - item2) >= 0 ? item1 - item2 : item2 - item1
      result = temp if result.nil? || temp < result
    end
  end
  result
end

关于如何改进这个的任何想法?

3 个答案:

答案 0 :(得分:9)

解决方案是对数组进行排序,然后迭代它。您现在只需要检查邻近(arr[i],arr[i+1])的候选者,而不是每对元素。

这在O(NlogN)中运行。

请注意,这是Element Distinctness Problem的概括,因此如果您对最差情况表现感兴趣,则效果不会超过O(NlogN)

答案 1 :(得分:3)

amit发布的解决方案正确n*log(n)时间,这是找到解决方案的最快时间。他的解决方案的ruby代码将看起来像这样:

def smallest_distance(a)
  sorted = array.sort
  shortest = 999999 # arbitrary large value
  for i in 0..sorted.length
    comparison = sorted[i+1] - sorted[i] if sorted[i+1] != nil
    if comparison < shortest
      shortest = comparison
    end
  end
  return shortest
end

答案 2 :(得分:2)

通常对于这种类型相关的问题。 如果您的算法等于或差于O(n ^ 2),您始终可以考虑使用排序算法来处理它。通常需要O(lgn),之后你可能会有一个线性算法。

对于此问题,您可以对此数组进行排序。然后只比较一个循环的相邻元素。 最终结果时间复杂度为O(n logn),这比您最初的想法更好。

所以你可以:

sorted = arr.sort

然后使用一个循环来压缩

arr[i] with ar[i+1]    from i = 0 ~ len-1
相关问题