给定两个整型数组,本题要求找出不是两者共有的元素。
输入分别在两行中给出两个整型数组,每行先给出正整数N(≤20),随后是N个整数,其间以空格分隔。
输出格式:
在一行中按照数字给出的顺序输出不是两数组共有的元素,数字间以空格分隔,但行末不得有多余的空格。题目保证至少存在一个这样的数字。同一数字不重复输出。
输入样例:
10 3 -5 2 8 0 3 5 -15 9 100
11 6 4 8 2 6 -5 9 0 100 8 1
输出样例
3 5 -15 6 4 1
看到这题第一想法是使用遍历法,将每一个元素拿出来和另一个数组的全部比较 ,但这样运行所需时间较多
换一种想法,在set集合中有contains可以快捷比较共同元素,于是
先创建数组,将数组的元素传递给集合,因为不知道非共同元素有多少,所以创建一个Arraylist链表来承载找出的非共同元素
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 读取输入的两个数组
int n1 = scanner.nextInt();
int[] arr1 = new int[n1];
for (int i = 0; i < n1; i++) {
arr1[i] = scanner.nextInt();
}
int n2 = scanner.nextInt();
int[] arr2 = new int[n2];
for (int i = 0; i < n2; i++) {
arr2[i] = scanner.nextInt();
}
// 使用集合进行筛选
Set<Integer> set1 = new HashSet<>();
for (int num : arr1) {
set1.add(num);
}
Set<Integer> set2 = new HashSet<>();
for (int num : arr2) {
set2.add(num);
}
// 找出不是两数组共有的元素
List<Integer> result = new ArrayList<>();
for (int num : arr1) {
if (!set2.contains(num)) {
if (!result.contains(num)) {//这是为了使同一数字只出现一次
result.add(num);
}
}
}
for (int num : arr2) {
if (!set1.contains(num)) {
if (!result.contains(num)) {
result.add(num);
}
}
}
// 输出结果
for (int i = 0; i < result.size(); i++) {
if (i > 0) {
System.out.print(" ");
}
System.out.print(result.get(i));
}
}
}