思路:
设计一个比较规则,让两个字符串假设说是m和n,如果组成的数字mn>nm,那么就返回nm,否则返回mn。
package Array;
import java.util.Arrays;
import java.util.Comparator;
public class MinNumber {
//方法一:用comparable接口实现
public String PrintMinNumber(int [] numbers)
{
String res = "";
if(numbers==null || numbers.length == 0)
{
return res;
}
MString m[] = new MString[numbers.length];
String st[] = Int2String(numbers);
int k=0;
for(String i:st){
m[k] = new MString();//!必须先赋值才能对它的成员变量进行访问
m[k++].s = i;
}
Arrays.sort(m);
for (int i = 0; i < m.length; i++) {
res+=m[i].s;
}
return res;
}
public String PrintMinNumber1(int [] numbers)
{
String res = "";
if(numbers==null || numbers.length == 0)
{
return res;
}
MString1 m[] = new MString1[numbers.length];
String st[] = Int2String(numbers);
int k=0;
for(String i:st){
m[k] = new MString1();//!必须先赋值才能对它的成员变量进行访问
m[k++].s = i;
}
MString1 c =new MString1();
Arrays.sort(m, c);
for (int i = 0; i < m.length; i++) {
res+=m[i].s;
}
return res;
}
//方法一 :必须要对进行比较的类T内部进行改造。首先实现接口 Comparable,(必须是T因为后面比较内部都是对对象进行的,否则出现类型转换错误)
//然后重写方法 compare(T t)即可。然后Arrays.sort(T[])自动回调用这个比较器
class MString implements Comparable<MString>{
public String s ;
public String toString() {
return s;
//"MString [s=" + s + "]";
}
@Override
public int compareTo(MString o) {
String s1 = s+o.s;
String s2 = o.s+s;
if(s1.compareTo(s2) > 0)
{
return 1;
}else if(s1.compareTo(s2) <0)
{
return -1;
}
else
{
return 0;
}
}
}
class MString1 implements Comparator<MString1>{
String s;
@Override
public int compare(MString1 o1, MString1 o2) {
String s1 = o1.s+o2.s;
String s2 = o2.s+o1.s;
if(s1.compareTo(s2) > 0){
return 1;
}else if(s1.compareTo(s2) <0)
return -1;
else return 0;
}
}
public String[] Int2String(int [] a)
{
String[] str = new String[a.length];
for(int i=0;i<a.length;i++)
{
str[i]=String.valueOf(a[i]);
}
return str;
}
public static void main(String[] args) {
MinNumber pms = new MinNumber();
int a[] = new int []{3,32,321};
/* System.out.println("测试方法一:用comparable接口实现");
System.out.println(pms.PrintMinNumber(a));*/
System.out.println("测试方法一:用comparator接口实现");
System.out.println(pms.PrintMinNumber1(a));
}
}