ruby-on-rails - 获取数组内元素的距离?

标签 ruby-on-rails algorithm time-complexity

我正在努力完成一个相当简单的任务,它有一个非负整数数组,我需要在其中返回最近的距离。

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

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

到目前为止,我只写了一个 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

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

最佳答案

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

这在 O(NlogN) 中运行。

请注意,这是 Element Distinctness Problem 的概括,所以如果您对最坏情况下的性能感兴趣,您无法获得比 O(NlogN) 更好的性能。

关于ruby-on-rails - 获取数组内元素的距离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29918709/

相关文章:

ruby-on-rails - 升级 Phusion Passenger 无需重新安装 Nginx

html - 垂直单元对齐

algorithm - 这个函数的时间复杂度是O(N)吗?

arrays - 直观地了解O(1)vs O(n)的时间复杂度

集合的 Javascript ES6 计算/时间复杂度

ruby-on-rails - 如何在 Rails 3 和 postgres 中处理大整数

ruby-on-rails - 自定义google plus url默认评论

algorithm - 撤消/重做实现

algorithm - 匹配算法

sql - 如何在SQL中选择相似的集合