解法一:
HashSet
=>List
列表
Collections.sort(list)
对列表进行排序
import java.util.*;
import java.util.HashSet;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (sc.hasNextInt()) { // 注意 while 处理多个 case
int n = sc.nextInt();
int[] arr1=new int[n];
for(int i=0;i<n;i++){
arr1[i]=sc.nextInt();
}
int m = sc.nextInt();
int[] arr2=new int[m];
for(int i=0;i<m;i++){
arr2[i]=sc.nextInt();
}
//hashset
HashSet<Integer> hashSet=new HashSet<Integer>();
for(int i=0;i<n;i++){
if(!hashSet.contains(arr1[i])){
hashSet.add(arr1[i]);
}
}
for(int i=0;i<m;i++){
if(!hashSet.contains(arr2[i])){
hashSet.add(arr2[i]);
}
}
// 转换为列表并排序
List<Integer>sortList=new ArrayList<>(hashSet);
//列表排序
Collections.sort(sortList);
//输出列表各个元素
for(int a:sortList){
System.out.print(a);
}
}
}
}
解法二:
一种数据结构满足既可以去重又可以排序
TreeSet
很好的满足了这次题目的需求,TreeSet
的底层是TreeMap
,TreeMap
的实现就是红黑树数据结构
import java.util.*;
import java.util.HashSet;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (sc.hasNextInt()) { // 注意 while 处理多个 case
int n = sc.nextInt();
Set<Integer> treeSet=new TreeSet<>();
for(int i=0;i<n;i++){
treeSet.add(sc.nextInt());
}
int m=sc.nextInt();
for(int i=0;i<m;i++){
treeSet.add(sc.nextInt());
}
for(Integer integer:treeSet){
System.out.print(integer);
}
}
}
}