How to compare two arrays of integers order-insensitively

前端 未结 8 1260
梦谈多话
梦谈多话 2021-01-19 13:23

I want Java code that can compare in this way (for example):

<1 2 3 4>  = <3 1 2 4>
<1 2 3 4> != <3 4 1 1>

I can\'t

8条回答
  •  既然无缘
    2021-01-19 13:49

    Before you actually start a more computationally complex solution, you can run a fast O(n) test to see if the arrays are the same. There are times when this this will result in a false positive, and you can use more computationally intensive means to investigate further. If it returns false, you can be assured that the arrays are different.

    The basic approach is to do a cummulative XOR between the ith elements of the two arrays. If the resulting XOR is non-zero then you know that the two arrays are different. If the XOR is zero, they might be the same, but more work is needed to confirm.

    int c_xor = 0;  // XOR accumulator
    
    for (int i = 0; i < n; ++i)
        c_xor ^= arr1[i] ^ arr2[i];
    
    // They're different if c_xor != 0; the might be the same if c_xor == 0
    return c_xor == 0;

提交回复
热议问题