我想要一个核心java程序来查找两个数组之间的唯一元素。 例: Array1 - 9,5,3,23,2,5 Array2 - 19,5,3,23,24,53
来自两个阵列的唯一元素的输出应打印为:9,2,19,24,53
请帮我用精确的循环编写程序。
注意:不要使用任何集合处理相同的程序,并且希望仅使用循环来完成。感谢
答案 0 :(得分:1)
您需要根据法律整数的范围来调整counter
数组和offset
变量的大小。但这不会使用java.util
中的任何内容API,只有循环。
public static int[] uniques(int[] array1, int[] array2) {
// assuming your integers are 0-53, you'd have to modify this if it's different
int[] counter = new int[54];
// offset needs to be changed based on if negative numbers are allowed
int offset = 0;
for(int i = 0; i < array1.length; i++) {
counter[array1[i] + offset]++;
}
for(int i = 0; i < array2.length; i++) {
counter[array2[i] + offset]++;
}
int numUniques = 0;
for(int i = 0; i < counter.length; i++) {
if(counter[i] == 1) numUniques++;
}
int[] uniqueArray = new int[numUniques];
int index = 0;
for(int i = 0; i < counter.length; i++) {
if(counter[i] == 1) uniqueArray[index++] = i;
}
return uniqueArray;
}