Check if two arrays have the same contents (in any order)

前端 未结 9 1729
我在风中等你
我在风中等你 2020-12-24 04:13

I\'m using Ruby 1.8.6 with Rails 1.2.3, and need to determine whether two arrays have the same elements, regardless of whether or not they\'re in the same order. One of the

9条回答
  •  悲哀的现实
    2020-12-24 04:57

    If you know the arrays are of equal length and neither array contains duplicates then this works too:

    ( array1 & array2 ) == array1
    

    Explanation: the & operator in this case returns a copy of a1 sans any items not found in a2, which is the same as the original a1 iff both arrays have the same contents with no duplicates.

    Analyis: Given that the order is unchanged, I'm guessing this is implemented as a double iteration so consistently O(n*n), notably worse for large arrays than a1.sort == a2.sort which should perform with worst-case O(n*logn).

提交回复
热议问题