Get index of array element faster than O(n)

前端 未结 8 1326
春和景丽
春和景丽 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 09:59

    Other answers don't take into account the possibility of an entry listed multiple times in an array. This will return a hash where each key is a unique object in the array and each value is an array of indices that corresponds to where the object lives:

    a = [1, 2, 3, 1, 2, 3, 4]
    => [1, 2, 3, 1, 2, 3, 4]
    
    indices = a.each_with_index.inject(Hash.new { Array.new }) do |hash, (obj, i)| 
        hash[obj] += [i]
        hash
    end
    => { 1 => [0, 3], 2 => [1, 4], 3 => [2, 5], 4 => [6] }
    

    This allows for a quick search for duplicate entries:

    indices.select { |k, v| v.size > 1 }
    => { 1 => [0, 3], 2 => [1, 4], 3 => [2, 5] }
    

提交回复
热议问题