【问题标题】:What's the most efficient way to manipulate Arrays in Ruby在 Ruby 中操作数组的最有效方法是什么
【发布时间】:2021-07-24 19:50:47
【问题描述】:

我正在尝试使以下代码更高效,但没有想法,因此寻求一些帮助:

我收到一个区间x 和一个整数数组space,我需要将space 数组分成x 区间的段,例如如果

space = [1, 2, 3, 1, 2]
x = 2
# The intervals Would be
[1, 2][2, 3][3, 1][1, 2]

那么我需要找到每个区间的最小值,然后找到最小值的最大值,所以在上面的示例中,最小值将是:

[1, 2, 1, 1]

然后我需要返回最小值的最大值2

以下是我的解决方案,大多数测试用例都通过了,但其中一些测试用例失败了,因为超出了执行时间。关于如何使以下代码更高效的任何想法?

def segment(x, space)
    minimums = {}
    space.each_with_index do |_val, index|
        # 1 Create the segment
        mark = x - 1
        break if mark >= space.length 
        segment = space[index..mark]
        x = x + 1    
        # 2 Find the min of the segment
        minimum = segment.min
        minimums[index] = minimum
    end
    
    # Compare the maximum of the minimums
    return minimums.values.max
end

我尝试将 minimums 设为哈希而不是数组,但没有成功。另外我想我会将space 数组转换为哈希并操作哈希而不是数组,但我认为这会更复杂......

【问题讨论】:

    标签: arrays ruby


    【解决方案1】:

    您不需要收集细分并在以后处理它们。只需遍历数组一次,同时保持每个段的最大最小值。

    另外each_with_index 也是一种浪费。只需自己遍历数组即可连续切片。

    简单示例:

    # initial conditions
    space = [1, 2, 3, 1, 2]
    x = 2
    # here we go
    min = space.min
    (0..space.length-x).each do |i|
      min = [space[i,x].min, min].max
    end
    puts min
    

    像往常一样,在 ruby​​ 中,总有一种更优雅的方式。例如,不需要创建切片;让 ruby​​ 来做 (each_cons):

    # initial conditions
    space = [1, 2, 3, 1, 2]
    x = 2
    # here we go
    min = space.min
    space.each_cons(x) do |slice|
      min = [slice.min, min].max
    end
    puts min
    

    当然,一旦您了解了它的工作原理,就可以进一步完善它(例如,如下面的评论所示)。

    【讨论】:

    • 你也可以写space.each_cons(2).max_by(&:min).min
    • 正如我所说,总有更优雅的方式!
    猜你喜欢
    • 2011-12-06
    • 1970-01-01
    • 2015-11-08
    • 2011-07-13
    • 2013-04-28
    • 1970-01-01
    • 2014-06-20
    • 2020-09-07
    • 2018-02-08
    相关资源
    最近更新 更多