Problem Description
给你两个集合,要求{A} + {B}.
注:同一个集合中不会有两个相同的元素.
注:同一个集合中不会有两个相同的元素.
Input
每组输入数据分为三行,第一行有两个数字n,m(0<n,m<=10000),分别表示集合A和集合B的元素个数.后两行分别表示集合A和集合B.每个元素为不超出int范围的整数,每个元素之间有一个空格隔开.
Output
针对每组数据输出一行数据,表示合并后的集合,要求从小到大输出,每个元素之间有一个空格隔开.
Sample Input
1 2 1 2 3 1 2 1 1 2
Sample Output
1 2 3 1 2题意:给出两个集合,求并集,集合中不能有相同的元素思路:用TreeSet,在加入时判断集合中是否包含该元素,没有就加入代码如下import java.io.FileInputStream; import java.io.OutputStreamWriter; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; import java.util.Iterator; public class Main implements Runnable { private static final boolean DEBUG = false; private Scanner cin; private PrintWriter cout; private int n, m; private void init() { try { if (DEBUG) { cin = new Scanner(new InputStreamReader(new FileInputStream("f:\\OJ\\uva_in.txt"))); } else { cin = new Scanner(new InputStreamReader(System.in)); } cout = new PrintWriter(new OutputStreamWriter(System.out)); } catch (Exception e) { e.printStackTrace(); } } private boolean input() { if (!cin.hasNextInt()) return false; n = cin.nextInt(); m = cin.nextInt(); return true; } private void solve() { Set<Integer> set = new TreeSet<Integer>(); for (int i = 0; i < n; i++) { set.add(cin.nextInt()); } for (int i = 0; i < m; i++) { int tmp = cin.nextInt(); if (!set.contains(tmp)) set.add(tmp); } Iterator<Integer> it = set.iterator(); boolean first = true; while (it.hasNext()) { if (first) first = false; else cout.print(" "); cout.print(it.next()); } cout.println(); cout.flush(); } @Override public void run() { init(); while (input()) { solve(); } } public static void main(String[] args) { // TODO code application logic here new Thread(new Main()).start(); } }