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
样例输入
4
1 2 3 4
3
5 6 7
样例输出
1 2 3 4 5 6 7
1 2 3 4

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Scanner;
import java.util.TreeSet;

public class Main {
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		ArrayList<Integer> N=new ArrayList<Integer>();
		int n=sc.nextInt();
		ArrayList<Integer> A=new ArrayList<Integer>();
		TreeSet<Integer> s=new TreeSet<Integer>();
		
		for(int x=0;x<n;x++) {
			A.add(sc.nextInt());
			s.add(A.get(x));
		}
		
		int m=sc.nextInt();
		ArrayList<Integer> B=new ArrayList<Integer>();
		for(int x=0;x<m;x++) {
			B.add(sc.nextInt());
			s.add(B.get(x));
		}
		int z=Math.min(n,m);
		for(int x=0;x<z;x++) {
			if(n<m) {
				if(B.indexOf(A.get(x))!=-1)
					N.add(A.get(x));
			}else {
				if(A.indexOf(B.get(x))!=-1)
					N.add(B.get(x));
			}
		}
		Collections.sort(N);
		for(int x=0;x<N.size();x++)
			System.out.print(N.get(x)+" ");
		System.out.println();
		
		Iterator it=s.iterator();
		while(it.hasNext())
			System.out.print(it.next()+" ");
		System.out.println();
		int i=0;
		while(i!=N.size())A.remove(N.get(i++));
		
		Collections.sort(A);
		for(int x=0;x<A.size();x++) 
			System.out.print(A.get(x)+" ");
	}
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值