打印两个int数组中的公共元素而不重复〔初学者〕



我很感激一些提示,这样我就能走上正轨。我正在尝试打印两个int数组中的公共值,而不重复。我不能使用任何字符串、集合、额外数组或操作现有数组,只能使用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 3 0 1-8 2
-我想打印的内容(订单可能不同(:0 2 6 9 1-3

我的一个想法是使用另一个for循环检查第一个数组是否重复,如果它不是重复的,只继续到主循环(检查公共元素(,但我不知道如何进行,也不知道它是否可行。到目前为止,我实现这个想法的所有尝试都失败了。

我用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?
}
}
}

我对如何解决这个问题有很多想法,但任务规则已经成功地禁止了我所有可能的解决方案,请帮助

  1. 通过
  2. 我们应该检查这个数字以前是否出现在
  3. 如果是,忽略它
  4. 如果没有,我们应该检查b中是否存在
  5. 如果是,请打印

这是代码。我没有检查。但我认为它应该有效。我想,总体思路很清楚。

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;
}
}
}
}
  1. 在第一个数组上迭代
    1. 检查当前元素以前是否出现在第一个数组中
      1. 如果不是:检查元素是否出现在第二个数组中,如果是,则打印它

这应该可以防止输出中出现任何重复值。

如果您想要一种懒惰、有效和简短的方法,那么请使用数据结构来存储公共值,并使用不允许重复的数据结构,最好是Set

在以下示例中,我使用了TreeSet,因为除了不允许重复条目外,它还使用compareTo方法对值进行排序:

public static void main(String[] args) {
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 };
// prepare a data structure to store the common values
Set<Integer> commonValues = new TreeSet<>();
// then compare each value of a to each value of b
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
// and if they are equal,
if (a[i] == b[j]) {
// store one of the values in the set
commonValues.add(a[i]);
}
}
}
// then print all the values of the set
System.out.println("Common values of a and b (no duplicates, ordered ascending) are:");
commonValues.forEach(System.out::println);
}

这会输出以下内容:

Common values of a and b (no duplicates, ordered ascending) are:
-8
0
1
2
3
9
16

最新更新