解题思路:
一步一步理清思路即可,注意的是去重时判断条件用常量
注意事项:
参考代码:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
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();
}
//交集
ArrayList arrayList = new ArrayList<>();
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
arrayList.add(arr1[i]);
}
}
}
Collections.sort(arrayList);
for (Object a : arrayList) {
System.out.print(a + " ");
}
System.out.println();
//并集
//先将两个集合连接;然后去重
int[] arr3 = new int[arr1.length + arr2.length];
//拼接
int index = 0;
for (int i = 0; i < arr1.length; i++) {
arr3[index] = arr1[i];
index++;
}
for (int i = 0; i < arr2.length; i++) {
arr3[index] = arr2[i];
index++;
}
//去重
int l = arr3.length;//确定新数组长度
for (int i = 0; i < l - 1; i++) {
for (int j = i + 1; j < l; ) {
if (arr3[i] == arr3[j]) {
for (int k = j; k < l - 1; k++) {
arr3[k] = arr3[k + 1];
}
l--;
} else
j++;
}
}
//去重后的数组
int[] arr4 = Arrays.copyOf(arr3, l);
//排序
Arrays.sort(arr4);
for (int a : arr4) {
System.out.print(a + " ");
}
//余集
ArrayList arrayList1 = new ArrayList<>();
for (int i = 0; i < arr1.length; i++) {
boolean flag = true;
for (int j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
flag = false;
break;
}
}
if (flag) {
arrayList1.add(arr1[i]);
}
}
Collections.sort(arrayList1);
System.out.println();
for (Object a : arrayList1) {
System.out.print(a + " ");
}
}
}
0.0分
0 人评分
【偶数求和】 (C语言代码)浏览:460 |
2006年春浙江省计算机等级考试二级C 编程题(2) (C语言代码)浏览:383 |
C语言程序设计教程(第三版)课后习题5.7 (C语言代码)浏览:416 |
输入输出格式练习 (C语言代码)浏览:773 |
陶陶摘苹果2 (C++代码)浏览:578 |
1218题求大神帮忙看看怎么不能过浏览:759 |
C二级辅导-阶乘数列 (C语言代码)浏览:1831 |
C语言程序设计教程(第三版)课后习题10.7 (C++代码)浏览:666 |
C语言程序设计教程(第三版)课后习题6.8 (C语言代码)浏览:646 |
WU-IP判断 (C++代码)(一种有趣的实现方法)浏览:1572 |