我正在编写一个基本程序来比较两个数组中的数据。顺序无关紧要,重复的数字也不重要。目前的输出是说数组数据是相同的。由于阵列数据不同,这不是我想要发生的事情。这是代码,我现在所拥有的:不考虑大小或顺序的Java数组数据比较
public class Algorithm1{
public static void main (String[] args){
int[] array1 = {1, 2, 3};
int[] array2 = {1, 2, 3, 4, 5, 6};
int matchCount = 0;
boolean match = false;
for(int j = 0; j < array1.length;j++) {
for(int i = 0; i < array2.length;i++){
if(array1[j] == array2[i])
matchCount++;
}
}
if(matchCount >= array1.length && matchCount >= array2.length)
match = true;
if(match = true){
System.out.println("The data in the arrays is the same.");
}
else if(match = false){
System.out.println("The data in the arrays is different.");
}
}
}
所以你想要的是检查一个数组是否是另一个的子集? –
@ user3435566你可以尝试在它之前对它进行排序。这种方式的O(nlogn)更快。当使用两个for循环时,它将是O(n^2) – Dexters