gpt4 book ai didi

java - 查找2数组的不同元素

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:53:31 25 4
gpt4 key购买 nike

我尝试打印 2 个数组 A 和 B 之间的集合的非交集。但是,我遇到了如何打印 A 不同 B 上的元素的问题。这是我的示例代码:

public class Array {

public static void main(String[] args) {
for (int i = 0; i <= arrA.length - 1; i++) {
arrA[i] = sc.nextInt();
}
for (int i = 0; i <= arrB.length - 1; i++) {
arrB[i] = sc.nextInt();
}

boolean x = true;
int y = 0;
for (int i = 0; i < arrA.length; i++) {
for (int j = 0; j < arrB.length; j++) {
if (arrA[i] == arrB[j]) {
arrTestA[i] = true;
}else y = arrA[i];
}
}

for (int i = 0; i < arrA.length; i++) {
x = x && arrTestA[i];
}

if (x) {
System.out.println("All the elements of A contained in B.");
}else {
System.out.println("There are elements on A different B.");
System.out.println("The elements of A which is not in B = "); //My Problem
}

}
}

最佳答案

要实现这一点,您可以使用 CollectionsretainAll 方法。例如:

List<Integer> arrTestA = new ArrayList<>();
List<Integer> arrTestB = new ArrayList<>();

[...]

List<Integer> common = new ArrayList<>(arrTestA);
common.retainAll(arrTestB);

List<Integer> diff = new ArrayList<>();
for(Integer element : arrTestA)
if(!common.contains(element))
diff.add(element);

[here you print out elements of diff as The elements of A which is not in B]

预计到达时间:非收集尝试:

int[] arr1 = { 1, 11, 5, 9, 4, 3, 4, 8 };
int[] arr2 = { 1, 7, 5, 3, 4, 8 };

Arrays.sort(arr1);
Arrays.sort(arr2);

for (int i : arr1) {
boolean contains = false;
for (int j : arr2) {
if (i == j) {
contains = true;
break;
}
}
if (!contains)
System.out.println("Arr2 doesn't contain number: " + i);
}

...或者循环看起来像这样:

outer: for (int i : arr1) {
for (int j : arr2) {
if (i == j) {
continue outer;
}
}
System.out.println("Arr2 doesn't contain number: " + i);
}

这只是一种方法,但希望您明白这一点。

预计到达时间 2:在我的做法中,其实这些Array是不需要排序的。您可以简单地删除负责排序的代码行。

关于java - 查找2数组的不同元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40913840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com