查找有序数字数组中缺少的元素

时间:2016-05-05 05:33:25

标签: arrays ruby

我订购了数组array。如果符合以下情况,我会从e定义一个array 缺少的号码。

  • 对于v的某些元素arrayev + 1v - 1
  • e不是array
  • 的元素
  • e不小于0

例如,缺少以下元素:

array = [0, 1, 2, 4, 5, 6, 9, 10, 12, 13, 17]

是:

[3, 7, 8, 11, 14, 16, 18]

如何找到给定数组array中缺少的元素?

4 个答案:

答案 0 :(得分:3)

看起来你想要这样的东西:

array = [0, 1, 2, 4, 5, 6, 9, 10, 12, 13, 17]
possible_missing = array.flat_map {|e| [e-1, e+1]}.uniq
#=> [1, 0, 2, 3, 5, 4, 6, 7, 8, 10, 9, 11, 13, 12, 14, 16, 18]
diff = (possible_missing - array).select {|e| e >= 0}
#=> [3, 7, 8, 11, 14, 16, 18]

答案 1 :(得分:1)

执行此操作的最有效方法可能是使用inject.这允许您只在一次传递中构建一个新数组。它不是特别红宝石,因为你需要编写算法。而不是依赖于构建函数。但它可能是最有效的方式。

以下算法结束每次迭代,返回数组的最终值为n + 1,其中n是评估的最后一项。如果下一个项目将排除该项目,则将其替换为n + 1。如果下一个项目比前一个项目大2以上,它也会插入n-1。

present = [0, 1, 2, 4, 5, 6, 9, 10, 12, 13, 17]

present.inject([]) {|absent,n| 
    # If a number has been skipped at n -1 and n +1
    if (absent.empty? or absent.last < n - 1) && n > 0
       absent << n -1 << n + 1

    # if n-1 is already present or the new array is still empty, add n+1
    elsif absent.empty? or absent.last == n-1 
      absent << n + 1

    # if the last element of the absent list should be excluded because it is n, replace it with n+1
    elsif  absent.last == n
      # replace last absent with next
      absent[absent.length-1] = n + 1 
      absent

    # in all other cases do nothing
    else absent
    end
}

# => [3, 7, 8, 11, 14, 16, 18]

答案 2 :(得分:1)

arr = [0, 1, 2, 4, 5, 6, 9, 10, 12, 13, 17]

b = ([arr[0]-1,0].max..arr[-1]+1).to_a - arr
  #=> [3, 7, 8, 11, 14, 15, 16, 18] 
(b - b.each_cons(3).with_object([]) { |(c,d,e),f| f << d if e==c+2 })
  #=> [3, 7, 8, 11, 14, 16, 18]

答案 3 :(得分:0)

array = [0, 1, 2, 4, 5, 6, 9, 10, 12, 13, 17]
range = (0..(array.max + 1))
(range.to_a - array).select do |el| 
  [el-1, el+1].any?{|el2| array.include?(el2)}
end
# => [3, 7, 8, 11, 14, 16, 18]