我正在尝试编写代码以得到2个子集的称赞,交集……。
一切正常,但是当我进入“联合”部分时,我出了点问题,无法解决。
我正在尝试从数组A和数组B中取出所有int
并将它们存储在新数组uAB
中;该代码正在从数组A复制,但是我从数组B获得0。
L+M-countI
是先前数组A, B
及其交点的数组长度,而iAB
是指我之前写的交点数组及其工作。
int ou = 0;
int countUA = 0;
int countUB = 0;
int uAB[] = new int[L + M - countI];
for (int j = 0; j < A.length; j++) {
for (int k = 0; k < iAB.length; k++) {
if (A[j] == iAB[k])
countUA++;
}
if (countUA == 0) {
uAB[ou] = A[j];
ou++;
}
}
int ab = ou;
for (int j = 0; j < B.length; j++) {
for (int k = 0; k < A.length; k++) {
if (B[j] == A[k])
countUB++;
}
if (countUB == 0) {
uAB[ab] = B[j];
ab++;
}
}
答案 0 :(得分:0)
逻辑错误。您没有考虑公共元素,而是将它们从结果(即并集)中完全删除。 您需要至少考虑一次。
int ou = 0;
int present = 0;
// below are my dummy values
int[] A = new int[]{5,8,7,6,9,2,3,98};
int[] B = new int[]{6,9,2,3,63,123};
int[] iAB = new int[]{6,9,2,3};
int uAB[] = new int[10];
for (int j = 0; j < A.length; j++) {
for (int k = 0; k < uAB.length; k++) {
if (A[j] == uAB[k]) // check if its already present in the union set
present++;
}
if (ou < uAB.length && present == 0) {
uAB[ou] = A[j];
ou++;
}
present = 0; // reset the present flag for the next number
}
// System.out.println(ou);
// int ab = ou; no need to do this as ou will point to the place for the next insertion
for (int j = 0; j < B.length; j++) {
for (int k = 0; k < uAB.length; k++) {
if (B[j] == uAB[k]) // check if its already present in the union set
present++;
}
if (ou < uAB.length && present == 0) {
uAB[ou] = B[j];
ou++;
}
present = 0; // reset the present flag for the next number
}
for (int k = 0; k < uAB.length; k++) {
System.out.println(uAB[k]);
}
只是想一想:到目前为止,这很好,尽管您可以通过将重复的步骤分离到一个函数中并在需要时调用(例如,当我们检查联合集中是否存在该数字时),使代码更具可读性。