Algorithm to tell if two arrays have identical members

前端 未结 16 2912
渐次进展
渐次进展 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

    The best way is probably to use hashmaps. Since insertion into a hashmap is O(1), building a hashmap from one array should take O(n). You then have n lookups, which each take O(1), so another O(n) operation. All in all, it's O(n).

    In python:

    def comparray(a, b): 
        sa = set(a)
        return len(sa)==len(b) and all(el in sa for el in b)
    

提交回复
热议问题