最大数

随机输入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]);
		}
	}

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值