Java 集合运算
问题描述
给出两个整数集合A、B,求出他们的交集、并集以及B在A中的余集。
输入格式
第一行为一个整数n,表示集合A中的元素个数。
第二行有n个互不相同的用空格隔开的整数,表示集合A中的元素。
第三行为一个整数m,表示集合B中的元素个数。
第四行有m个互不相同的用空格隔开的整数,表示集合B中的元素。
集合中的所有元素均为int范围内的整数,n、m<=1000。
输出格式
第一行按从小到大的顺序输出A、B交集中的所有元素。
第二行按从小到大的顺序输出A、B并集中的所有元素。
第三行按从小到大的顺序输出B在A中的余集中的所有元素。
样例输入
5
1 2 3 4 5
5
2 4 6 8 10
样例输出
2 4
1 2 3 4 5 6 8 10
1 3 5
代码:
import java.util.Scanner;
public class Test {
public static String jiao(int a[], int b[]) {
String s = "";
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
if (a[i] == b[j]) {
s = s.concat(a[i] + "").concat(" ");
continue;
}
}
}
return s;
}
public static String bing(int a[], int b[]) {
String s = "";
for (int i = 0; i < a.length; i++) {
s = s.concat(a[i] + ""+" ");
}
for (int i = 0; i < a.length; i++) {
int count = 0;
for (int j =0;j<a.length;j++) {
if (a[j] != b[i]) {
count++;
}
if (count == a.length){
s = s.concat(b[i] + "" + " ");
}
}
}
return s;
}
public static String yu(int a[], int b[]){
String s = "";
for (int i = 0; i < a.length; i++) {
int count = 0;
for (int j = 0; j < a.length; j++) {
if(a[i] != b[j]){
count++;
}
if (count == a.length){
s = s.concat(a[i]+""+" ");
}
}
}
return s;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
int m = sc.nextInt();
int[] b = new int[n];
for (int i = 0; i < m; i++) {
b[i] = sc.nextInt();
}
String s = jiao(a, b);
System.out.println(s);
s = bing(a, b);
System.out.println(s);
s = yu(a,b);
System.out.println(s);
}
}
还没有评论,来说两句吧...