我必须按照以下标准解决一个练习:
比较两个数组:
int[] a1 = {1, 3, 7, 8, 2, 7, 9, 11};
int[] a2 = {3, 8, 7, 5, 13, 5, 12};
array int[]使用第一个数组中的唯一值创建一个新的。结果应如下所示:int[] result = {1,2,9,11};
注意:我不允许使用ArrayList或Arrays上课来解决此任务。
我正在使用以下代码,但填充循环的逻辑不正确,因为它引发了越界异常。
public static int[] removeDups(int[] a1, int[] a2) {
//count the number of duplicate values found in the first array
int dups = 0;
for (int i = 0; i < a1.length; i++) {
for (int j = 0; j < a2.length; j++) {
if (a1[i] == a2[j]) {
dups++;
}
}
}
//to find the size of the new array subtract the counter from the length of the first array
int size = a1.length - dups;
//create the size of the new array
int[] result = new int[size];
//populate the new array with the unique values
for (int i = 0; i < a1.length; i++) {
int count = 0;
for (int j = 0; j < a2.length; j++) {
if (a1[i] != a2[j]) {
count++;
if (count < 2) {
result[i] = a1[i];
}
}
}
}
return result;
}
我也很想知道如何用一个循环来解决这个问题(学习目的)。
慕码人8056858
慕莱坞森
Cats萌萌
Helenr
相关分类