Short answer
O (n + m) on average
O (nm), , , (. ).
array_one , array_two, O (m + n) O (n), .
Alternative
:
one = [1, "taco", 3, 2, :piece, 4, 5, 5, 5, 5]
two = [:piece, 2, 5, 4, 1, "taco", 3]
puts Set[*one] == Set[*two]
puts one.to_set == two.to_set
return true if x
return false
x
, :
def same_elements?(array_one, array_two)
(array_one - array_two).empty? && (array_two - array_one).empty?
end
Benchmark
1E6, 0 199999 ( ), - Ruby.
- , .
N = 1_000_000
one = (1..N).map{rand < 0.5 ? rand(N/5) : Object.new}
two = one.sort_by{rand}
1 , fruity , 20% , OP.
OP .
: , @engineersmnky , , , .
, , O(nm) .
:
rb_ary_diff array.c, , : .
rb_ary_diff - array_two ( O (m)) array_one ( O (n)), - (O ( 1) ). O (n + m).
, .
, O (n + m).
O (mn)
O (mn) - -. , , .
10_000 KeyObjects:
class KeyObject < Object
end
1 .
10_000 KeyObjects:
class KeyObject < Object
def hash
1
end
end
14 !
, Ruby , 1E-20. , O (mn), , . 2 , 1E6 .