我希望得到一些提示,以便我能够走上正确的道路。 我试图从两个 int 数组中打印公共(public)值而不重复。我无法使用任何字符串、集合、额外数组或操作现有数组,并且只能使用 java.lang 包。
这是我现在的代码:
int[] a = { 6, 0, 2, -7, 16, 9, 1, -8, 9, 9, 3, -9, -1, 0, 1, -8, 2, 99 };
int[] b = { 16, 0, 5, 2, -5, 3, 3, 9, 9, 1, -8, -8 };
for (int x : a) {
for (int y : b) {
if(x == y) {
System.out.print(x + " ");
break;
}
}
}
或
int[] a = { 6, 0, 2, -7, 16, 9, 1, -8, 9, 9, 3, -9, -1, 0, 1, -8, 2, 99 };
int[] b = { 16, 0, 5, 2, -5, 3, 3, 9, 9, 1, -8, -8};
int al = a.length;
int bl = b.length;
for (int x = 0; x < al; x++) {
for (int y = 0; y < bl; y++) {
if ( a[x] == b[y] ) {
System.out.print( a[x] + " ");
break;
}
}
}
-用我当前的代码打印什么:0 2 16 9 1 -8 9 9 3 0 1 -8 2
-我要打印的内容(顺序可能不同):0 2 16 9 1 -8 3
我的一个想法是使用另一个 for 循环检查第一个数组是否有重复项,如果它不是重复项,则仅继续主循环(检查公共(public)元素),但我不知道该怎么做这或者它是否可行。到目前为止,我所有实现这个想法的尝试都失败了。
我用 for 循环编写了一个代码片段来检查重复项(但不知道如何处理它):
int[] a = { 6, 0, 2, -7, 16, 9, 1, -8, 9, 9, 3, -9, -1, 0, 1, -8, 2, 99 };
int[] b = { 16, 0, 5, 2, -5, 3, 3, 9, 9, 1, -8, -8};
int al = a.length;
int bl = b.length;
for (int i = 0; i < al; i++) {
for (int j = i+1; j < al ; j++) {
// duplicates exist
if (a[i] == a[j] ) {
// not sure what to put here?
}
}
}
我对如何解决这个问题有多种想法,但任务规则已成功禁止我所有可能的解决方案,请帮忙
最佳答案
- 通过 a 进行迭代
- 我们应该检查该号码之前是否出现在
- 如果是,请忽略
- 如果不存在,我们应该检查b中是否存在
- 如果有,则打印
这是代码。 我没查。但我认为它应该有效。我想总体思路很清楚。
for (int i = 0; i < al; i++) {
flagDubl = false;
//!!here I've changed your code !!
for (int j = 0; j < i ; j++) {
// duplicates exist
if (a[i] == a[j] ) {
flagDubl = true;
break;
}
}
//ignore if it is dublicate
if (!flagDubl) {
for (int j = 0; j < bl; j++){
if (a[i] == b[j]) {
//it is in both arrays;
System.out.print( a[i] + " ");
break;
}
}
}
}
关于java - 打印两个 int 数组中的公共(public)元素而不重复 [初学者],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58732550/