How to compare two arrays of integers order-insensitively

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

    Sort & compare. You can't get the complexity better than that, and any "improvement" that you do on the speed comes at the risk that your code will be wrong.

    [edit] Actually.... if you know your numbers are relatively small (e.g. say: the arrays only contain numbers between 0 and 1000), that there's an alternative in O(n). Something like this (sorry if the syntax is wrong, I didn't use java lately):

    int count[1001]; // already intialized to 0
    
    for(int i=0;i

    Disclaimer: this code doesn't contain "sanity checks" (i.e. the arrays are really of length "n", the numbers are in the prescribed interval) - it's only to illustrate the principle.

提交回复
热议问题