题目描述
有一些数字,相互之间可能有重复,现在要对这些数进行去重,去重后还要排序。数字个数最多为1000个。
输出去重后的数字个数,并且输出排序后的数字
示例:
输入
10
20 30 40 50 60 70 80 20 30 40
输出
7
20 30 40 50 60 70 80
思路1:
用HashSet先去重,然后再对HashSet进行排序。
public class Main2 {
//hashset
public static void getRes(int[] arr) {
Set<Integer> treeSet = new TreeSet<>();
for (int i = 0; i < arr.length; i++) {
treeSet.add(arr[i]);
}
System.out.println(treeSet.size());
//System.out.println(treeSet);
Iterator it = treeSet.iterator();
while (it.hasNext()) {
System.out.print(it.next() + " ");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
getRes(arr);
}
sc.close();
}
}
思路2:
桶排序的思想,由于最多1000个数,那就设置1000个bin。
public class Main {
//桶排序
public static LinkedList<Integer> getArray(int[] arr) {
final int NUM = 1000;
int[] bucket = new int[NUM];
for (int i = 0; i < arr.length; i++) {
int index = arr[i] - 1;
if (bucket[index] == 0) {
bucket[index]++;
}
}
//遍历bucket,构造返回结果
LinkedList<Integer> list = new LinkedList<>();
for (int i = 0; i < NUM; i++) {
if (bucket[i] == 1) {
list.add(i + 1);
}
}
return list;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
LinkedList<Integer> list2 = getArray(arr);
System.out.println(list2.size());
for (int i = 0; i < list2.size(); i++) {
System.out.print(list2.get(i) + " ");
}
}
sc.close();
}
}