假设我有一个二维数组
A
,并且已知它的某个位置包含了一个对象my_element
。那么最快的方法是什么,可以找到这个对象的坐标?我正在使用Ruby 1.8.6。A
,并且已知它的某个位置包含了一个对象my_element
。那么最快的方法是什么,可以找到这个对象的坐标?我正在使用Ruby 1.8.6。这是一种方法。虽然我不确定它是否是最快的。
class Array
def coordinates(element)
each_with_index do |subarray, i|
j = subarray.index(element)
return i, j if j
end
nil
end
end
array = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
array.coordinates(3) # => [0, 2]
array.coordinates(9) # => [2, 2]
array.coordinates(42) # => nil
O(m*n)
,其中m
和n
是数组中行和列的数量。 - Bart Kiers