获取数组元素的索引比O(n)快 [英] Get index of array element faster than O(n)

查看:100
本文介绍了获取数组元素的索引比O(n)快的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于我有一个巨大的数组,以及它的值。我想得到数组中的值的索引。有没有其他方法,而是调用数组#index 来获取它?问题来自需要保持真正庞大的数组并且调用数组#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.

之后几次尝试我发现通过使用(值,索引)字段而不是值本身存储结构,缓存内部元素内的索引给了一个巨大的步骤在性能上(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆