比 O(n) 更快地获取数组元素的索引 [英] Get index of array element faster than O(n)
问题描述
鉴于我有一个巨大的数组,以及它的一个值.我想获取数组中值的索引.有没有其他方法,而不是调用 Array#index
来获取它?问题来自需要保留非常大的数组并调用 Array#index
大量时间.
Given I have a HUGE array, and a value from it. I want to get index of the value in array. Is there any other way, rather then call Array#index
to get it? The problem comes from the need of keeping really huge array and calling Array#index
enormous amount of times.
经过几次尝试后,我发现 缓存 通过使用 (value, index)
字段而不是值本身存储结构来缓存元素内部的索引,从而大大提高了性能(赢了 20 倍).
After a couple of tries I found that caching indexes inside elements by storing structs with (value, index)
fields instead of the value itself gives a huge step in performance (20x times win).
我仍然想知道是否有一种更方便的方法可以在不缓存的情况下找到 en 元素的索引(或者有一种很好的缓存技术可以提高性能).
Still I wonder if there's a more convenient way of finding index of en element without caching (or there's a good caching technique that will boost up the performance).
推荐答案
将数组转换为散列.然后寻找钥匙.
Convert the array into a hash. Then look for the key.
array = ['a', 'b', 'c']
hash = Hash[array.map.with_index.to_a] # => {"a"=>0, "b"=>1, "c"=>2}
hash['b'] # => 1
这篇关于比 O(n) 更快地获取数组元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!