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

前端 未结 14 824
盖世英雄少女心
盖世英雄少女心 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:08

    I'm not sure that correctly understood the problem, but if you are interested in integers that are in both array:

    If N >>>>> 2^SizeOf(int) (count of bit for integer (16, 32, 64)) there is one solution:

    a = Array(N); //length(a) = N;
    b = Array(M); //length(b) = M; 
    //x86-64. Integer consist of 64 bits.
    
    for i := 0 to 2^64 / 64 - 1 do  //very big, but CONST
      for k := 0 to M - 1 do
        if a[i] = b[l] then doSomething;   //detected
    
    for i := 2^64 / 64 to N - 1 do
     if not isSetBit(a[i div 64], i mod 64) then
       setBit(a[i div 64], i mod 64);
    
    for i := 0 to M - 1 do
     if isSetBit(a[b[i] div 64], b[i] mod 64) then doSomething; //detected
    

    O(N), with out aditional structures

提交回复
热议问题