Get index of array element faster than O(n)

前端 未结 8 1340
春和景丽
春和景丽 2020-12-07 09:28

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 p

8条回答
  •  星月不相逢
    2020-12-07 10:11

    Why not use index or rindex?

    array = %w( a b c d e)
    # get FIRST index of element searched
    puts array.index('a')
    # get LAST index of element searched
    puts array.rindex('a')
    

    index: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-index

    rindex: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-rindex

提交回复
热议问题