Algorithm to tell if two arrays have identical members

前端 未结 16 2997
渐次进展
渐次进展 2020-11-29 06:52

What\'s the best algorithm for comparing two arrays to see if they have the same members?

Assume there are no duplicates, the members can be in any order, and that n

16条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 07:04

    Assuming you don't want to disturb the original arrays and space is a consideration, another O(n.log(n)) solution that uses less space than sorting both arrays is:

    1. Return FALSE if arrays differ in size
    2. Sort the first array -- O(n.log(n)) time, extra space required is the size of one array
    3. For each element in the 2nd array, check if it's in the sorted copy of the first array using a binary search -- O(n.log(n)) time

    If you use this approach, please use a library routine to do the binary search. Binary search is surprisingly error-prone to hand-code.

    [Added after reviewing solutions suggesting dictionary/set/hash lookups:]

    In practice I'd use a hash. Several people have asserted O(1) behaviour for hashes, leading them to conclude a hash-based solution is O(N). Typical inserts/lookups may be close to O(1), and some hashing schemes guarantee worst-case O(1) lookup, but worst-case insertion -- in constructing the hash -- isn't O(1). Given any particular hashing data structure, there would be some set of inputs which would produce pathological behaviour. I suspect there exist hashing data structures with the combined worst-case to [insert-N-elements then lookup-N-elements] of O(N.log(N)) time and O(N) space.

提交回复
热议问题