首页 > 技术文章 > 算法训练 集合运算

maxin 2016-05-19 19:09 原文

问题描述
  给出两个整数集合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

锦囊1

排序后处理。

锦囊2

先排序,对于每个集合的操作,都使用两个指针来指向排序后的集合,对于相同元素特别处理。

Java测试代码

 1 package cn.maxin.test;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collections;
 5 import java.util.List;
 6 import java.util.Scanner;
 7 
 8 public class Main {
 9 
10     public static void main(String[] args) {
11 
12         Scanner sc = new Scanner(System.in);
13 
14         int m = sc.nextInt();
15         List<Integer> ListA = new ArrayList<Integer>();
16         for (int i = 0; i < m; i++) {
17             ListA.add(sc.nextInt());
18         }
19         int n = sc.nextInt();
20         List<Integer> ListB = new ArrayList<Integer>();
21         for (int i = 0; i < n; i++) {
22             ListB.add(sc.nextInt());
23         }
24         sc.close();
25 
26         List<Integer> ListU = new ArrayList<Integer>();
27         ListU.addAll(ListB);
28         ListB.retainAll(ListA);
29         ListA.removeAll(ListB);
30         ListU.addAll(ListA);
31         
32         Collections.sort(ListA);
33         Collections.sort(ListB);
34         Collections.sort(ListU);
35 
36         for (int i = 0; i < ListB.size(); i++) {
37             System.out.print(ListB.get(i));
38             System.out.print(i == ListB.size() - 1 ? "\r\n" : ' ');
39         }
40         for (int i = 0; i < ListU.size(); i++) {
41             System.out.print(ListU.get(i));
42             System.out.print(i == ListU.size() - 1 ? "\r\n" : ' ');
43         }
44         for (int i = 0; i < ListA.size(); i++) {
45             System.out.print(ListA.get(i));
46             System.out.print(i == ListA.size() - 1 ? "\r\n" : ' ');
47         }
48     }
49 }

 

 

推荐阅读