随机输入10个小于10 的整数,有可能重复,找出3个不同的数,并输出能组合的最大的数。比如输入1 2 3 4 5 6 7 8 9 0;输出987
方法一:利用TreeSet降序
import java.util.*;
public class Main {
static Main m = new Main();
private class Num implements Comparable{
int value;
public Num(int n){
this.value = n;
}
public boolean equals(Object o)
{
return false;
}
public int compareTo(Object o) {
Num n = (Num)o;
if(this.value>n.value)
return -1;
else if(this.value<n.value)
return 1;
else
return 0;
}
}
public static void main(String[] args) {
TreeSet<Num> set = new TreeSet<Num>();
int n = 10;
Scanner scan = new Scanner(System.in);
while (n-->0) {
Num n1 = m.new Num(scan.nextInt());
set.add(n1);
}
Iterator<Num> it = set.iterator();
int index = 3;
while (it.hasNext()&&index-->0) {
System.out.print(it.next().value);
}
}
}
本方法采取了TreeSet降序的方法,因为TreeSet默认自然升序,若自定义排序,需要实现Comparable接口,并覆盖CompareTo方法。
方法二:直接使用TreeSet
import java.util.*;
public class Main1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeSet<Integer> set = new TreeSet<Integer>();
int n = 10;
Scanner scan = new Scanner(System.in);
while (n-->0) {
set.add(scan.nextInt());
}
int len = set.size();
int []a = new int[len];
int index = 0;
Iterator<Integer> it = set.iterator();
while (it.hasNext()&&index<len) {
a[len-1-index] = it.next();
index++;
}
for (int i = 0; i < 3; i++) {
System.out.print(a[i]);
}
}
}