Is there a faster way to compare two int arrays in Java?

I have two arrays of integers of the same size, such as n (n is variable, so I can have two arrays of sizes, such as 4 or 5 or 6). The value range of each number is 0-9

Integer[] one = {1,9,3,4} 
Integer[] two = {1,1,3}

Now, I want to compare number one and number one. 1) I can get the same number of elements in the same position 2) I can get the same number count but not in the same position

My approach is

For (1) iterative array 1 and for each index, I check a [i] = = two [i]. – simple

Iterate over two arrays for (2) and for I= j. Check whether the elements are the same, and if so, mark them as - 1 to avoid future conflicts

for(int i =0;i<one.length;i++){
    for(int j=0;j<two.length;j++){
        if(i != j && one[i] != -1 && two[j] !=-1)){
            if(one[i] == two[j]){
                whiteCount++
                one[i] = -1;
                two[j] = -1;
            }
        }
    }
}

Q: now I wonder if there is a faster way to do the same thing? Esp. part (2) of the calculation problem This is the basic comparison method to obtain the black and white nail calculation of mastermind desktop game Thank you, Shakti

Update 1:1) Rudi's suggestion to change integer [] to int []

2) Using Dave Challis's solution, performance changes are calculated for 7776 x 7776

OLD 46950 ms
NEW 42887 ms

Solution

Although this may not be what you want, we can significantly reduce the number of operations through very simple changes

from

Integer[] one = {1,3}

to

int[] one = {1,4} 
int[] two = {1,3}

This will speed up the process a little, but not by optimizing the sorting / search logic itself What we do is to delete automatic packing and automatic unpacking But if you do this on such a large scale, it can make a substantial difference

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>