Check if 2 arrays are similar without hashing or sorting

后端 未结 4 1058
南旧
南旧 2021-01-13 10:20

We need to check if 2 arrays are similar or not. The elements can be duplicate as well. For example A = {2,3,4,5,6,6} and B = {3,6,2,4,6,5} are similar.

I have a nai

相关标签:
4条回答
  • 2021-01-13 10:32

    You can do it in O(max(LA, LB)) time, where LA and LB are lengths of A and B, respectively, but at the price of using O(M) space, where M is an allowed range of values in the arrays (i.e. there are such constants min and max, so that min <= a, b <= max holds true for every a in A and b in B).

    seen = array[min..max]
    foreach a in A
        seen[a] = 'a'
    
    foreach b in B
        if seen[b] != 'a'
            // A didn't contain b
            return "A and B are not equivalent"
        else
           seen[b] = 'a,b'
    
    foreach s in seen
        if s == 'a'
            // A did contain a which was not in B
            return "A and B are not equivalent"
    
    return "A and B are equivalent"
    

    This approach is practical if the arrays are very large, but all their values fit in a small range.

    0 讨论(0)
  • 2021-01-13 10:37

    A = {2,3,4, 5,-1,6} and B = {3,6,2,4,6,5}

    you should add break in your if-statement, without it your code will work only is there is no duplicates

    0 讨论(0)
  • 2021-01-13 10:47

    You can use a binary search tree that you build from one of them. Now go over the other one and check if the value is already in the binary search tree. This one runs in O(nlgn) and use O(n) space.

    0 讨论(0)
  • 2021-01-13 10:55

    i just want to mention that u don't have to run your algorithm(whether it has a complexity of o(n*m) or max(n,m)) for all input combinations.Run your algorithm only if xor of all the elements of both arrays is equal to zero. i.e a[0] xor a[1] xor...b[0] xor...b[n]=0. otherwise u can surely say that array A and B is not equal.

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