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

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

    0 讨论(0)
  • 2020-12-02 18:10

    why not i find the sum , product , xor of all the elements one array and compare them with the corresponding value of the elements of the other array ??

    the xor of elements of both arrays may give zero if the it is like

    2,2,3,3 1,1,2,2

    but what if you compare the xor of the elements of two array to be equal ???

    consider this

    10,3 12,5

    here xor of both arrays will be same !!! (10^3)=(12^5)=9 but their sum and product are different . I think two different set of elements cannot have same sum ,product and xor ! This can be analysed by simple bitvalue examination. Is there anything wrong in this approach ??

    0 讨论(0)
提交回复
热议问题