试题 算法训练 集合运算

Lan
Lan
2020-03-19 / 1 评论 / 657 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2020年03月19日,已超过1492天没有更新,若内容或图片失效,请留言反馈。
资源限制
时间限制:1.0s   内存限制:512.0MB
问题描述
  给出两个整数集合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.*;
public class jiheyunsuan {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		//按照条件获取输入的值
		int n = sc.nextInt();
		int[] list1 = new int[n];
		for (int i = 0; i < list1.length; i++) {
			list1[i]= sc.nextInt();
		}
		int m = sc.nextInt();
		int[] list2 = new int[m];
		for (int i = 0; i < list2.length; i++) {
			list2[i]= sc.nextInt();
		}
		//创建三个列表用于装结果
		ArrayList<Integer> jiaoji =new ArrayList<Integer>();
		ArrayList<Integer> bingji =new ArrayList<Integer>();
		ArrayList<Integer> buji =new ArrayList<Integer>();
		//第一层循环,遍历list1
		for (int i = 0; i < list1.length; i++) {
			//布尔型的bu表示,默认为这个数是list2在list1中的余集
			boolean bu = true;
			//如果bingji中不包含list1[i]的值,就加到并集中去
			if (!bingji.contains(list1[i])) {
				bingji.add(list1[i]);
			}
			for (int j = 0; j < list2.length; j++) {
				//如果bingji中不包含list2[i]的值,就加到并集中去
				if (!bingji.contains(list2[j])) {
					bingji.add(list2[j]);
				}
				//判断交集
				if (list1[i]==list2[j]&&!jiaoji.contains(list1)) {
						jiaoji.add(list1[i]);
				}
				//判断余集
				if (list1[i]==list2[j]) {
					bu=false;
				}
			}
			//如果补集中不存在则加入列表
			if (bu&&!buji.contains(list1[i])) {
				buji.add(list1[i]);
			}
		}
		//列表排序
		Collections.sort(jiaoji);
		Collections.sort(bingji);
		Collections.sort(buji);
		//遍历输出
		for (int j = 0; j < jiaoji.size(); j++) {
			System.out.print(jiaoji.get(j)+" ");
		}
		if (jiaoji.size()!=0) {
			System.out.println();
		}
		for (int j = 0; j < bingji.size(); j++) {
			System.out.print(bingji.get(j)+" ");
		}
		if (bingji.size()!=0) {
			System.out.println();
		}
		for (int j = 0; j < buji.size(); j++) {
			System.out.print(buji.get(j)+" ");
		}
		
	}
}


0

评论 (1)

取消
  1. 头像
    asdasdasdasd
    Windows 10 · Google Chrome

    123

    回复