find if two arrays contain the same set of integers without extra space and faster than NlogN

前端 未结 14 839
盖世英雄少女心
盖世英雄少女心 2020-12-02 17:27

I came across this post, which reports the following interview question:

Given two arrays of numbers, find if each of the two arrays have the same s

14条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 18:07

    You can try a probabilistic approach by choosing a commutative function for accumulation (eg, addition or XOR) and a parametrized hash function.

    unsigned addition(unsigned a, unsigned b);
    unsigned hash(int n, int h_type);
    
    unsigned hash_set(int* a, int num, int h_type){
        unsigned rez = 0;
        for (int i = 0; i < num; i++)
            rez = addition(rez, hash(a[i], h_type));
        return rez;
    };
    

    In this way the number of tries before you decide that the probability of false positive will be below a certain treshold will not depend on the number of elements, so it will be linear.

    EDIT: In general case the probability of sets being the same is very small, so this O(n) check with several hash functions can be used for prefiltering: to decide as fast as possible if they are surely different or if there is a probability of them being equivalent, and if a slow deterministic method should be used. The final average complexity will be O(n), but worst case scenario will have the complexity of the determenistic method.

提交回复
热议问题