我想创建一个方法,该方法可以检查两个数组是否相同(不使用任何导入)。顺序无关紧要,它可以包含重复项,并且两个数组必须保持相同!我的想法是复制第一个数组,然后将复制的数组与第二个数组进行比较。如果我找到有效的一对,请从复制数组中删除该项目,以便它可以处理重复项。但是由于类型不匹配,我无法删除任何项目。我的代码:
Solution.java
public class Solution {
public static boolean areTheyTheSame(int[] a,int[] b)
{
if (a.length == b.length)
{
//fill the temp array with the elements of a
int temp[] = new int[a.length];
for (int i = 0 ; i < a.length ; i++)
{
temp[i] = a[i];
}
//check if the temp array and the b array are the same
for (int i = 0 ; i < a.length ; i++)
{
for (int j = 0 ; j < a.length ; j++)
{
if (temp[i] == b[j])
{
temp[i] = null; // Type mismatch: cannot convert from null to int
}
else
{
return false;
}
}
}
return true;
}
return false;
}
}
Test.java
public class Test {
public static void main(String[] args) {
int[] a = new int[]{121,144,19,161,11};
int[] b = new int[]{121,11,19};
if (Solution.areTheyTheSame(a,b) == true)
{
System.out.println("Equal");
}
else
{
System.out.println("Not equal");
}
}
}