How to compare two arrays of integers order-insensitively

前端 未结 8 1079
梦谈多话
梦谈多话 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:35

    Here is a fix for the code that you posted.

    for(int i = 0; i < n; i++)
    {
        int j;
        for(j = 0; j < n; j++)
        {   
            if(a[i] == b[j]) break;
        }
        if (j == n) return false;
    }
    return true;
    

    That algorithm is going to break done for arrays that contain duplicates, however. For example, the array {1, 1, 2, 3} will be found as a match to the array {1, 2, 2, 3}.

    I would highly recommend that you implement a sort-and-compare algorithm instead.

提交回复
热议问题