我需要检查测试用例的状态,例如它是通过还是失败,并知道它的索引值。
我怎样才能做到这一点?
我尝试了二分搜索。这是代码:
class Array
def binary_search(val, low = 0, high = length - 1)
return nil if high < low
mid = (low + high) >> 1
case val <=> self[mid]
when -1
binary_search(val, low, mid - 1)
when 1
binary_search(val, mid + 1, high)
else
mid
end
end
end
ary = [0, 1, 4, 5, 6, 7, 8, 9, 12, 26, 45, 67, 78, 90]
[0, 42, 45, 24324, 99999].each do |val|
i = ary.binary_search(val)
if i
puts "found #{val} at index #{i}: #{ary[i]}"
else
puts "#{val} not found in array"
end
end
但这是关于是否找到钥匙。
答案 0 :(得分:0)
您可能希望考虑以下事项。
ary = [0, 1, 4, 5, 6, 7, 8, 9, 12, 26, 45, 67, 78, 90]
a = [0, 42, 45, 24324, 99999]
h = ary.each_with_index.to_h
#=> {0=>0, 1=>1, 4=>2, 5=>3, 6=>4, 7=>5, 8=>6, 9=>7, 12=>8, 26=>9,
# 45=>10, 67=>11, 78=>12, 90=>13}
a.each do |val|
i = h[val]
puts i ? "found #{val} at index #{i}: #{ary[i]}" : "#{val} not found in array"
end
found 0 at index 0: 0
42 not found in array
found 45 at index 10: 45
24324 not found in array
99999 not found in array
使用哈希可以快速查找密钥,并在h
中匹配a
个匹配值。