题目描述
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
import java.util.*;
public class 把数组排成最小的数 {
public static void main(String[] args) {
int[] test = {3,32,321};
System.out.print(PrintMinNumber(test));
}
//方法一 重新定义比较方法
public static String PrintMinNumber(int [] numbers){
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = 0; i < numbers.length; i++)
al.add(numbers[i]);
Collections.sort(al,new Comparator<Integer>(){//重写排序的依据
public int compare(Integer o1,Integer o2){
String s1 = o1+""+o2;
String s2 = o2+""+o2;
return s1.compareTo(s2);//按字典序比较s1和s2不相同的索引号最小的两个字符,s1>s2返回正数,s1==s2返回0,s1<s2返回负数,
}
});
String res = "";
for (int x:al)
res = res + x;
return res;
}
//方法二 暴力解出全排列 然后选出最小******************************************************************
public static String PrintMinNumber(int [] numbers) {
if(numbers==null || numbers.length==0)
return "";
ArrayList<Long> al = new ArrayList<Long>();
helper(numbers, 0, al);
long res = al.get(0);
for (long x:al) {
if(x<res)
res =x;
}
return res+"";
}
public static void helper(int numbers[],int begin,ArrayList<Long> al){
if(begin == numbers.length-1){//数组全排列中的一个已完成
long tmp = arrToInt(numbers);//将整个数组转换成某种
if(!al.contains(tmp))
al.add(tmp);
return;
}
else{
for(int i = begin;i<numbers.length;i++){
swap(numbers, begin, i);
helper(numbers,begin+1,al);//注意这里是begin+1,不是i+1
swap(numbers, begin, i);
}
}
}
public static long arrToInt(int a[]){
String str = "";
for (int i = 0; i < a.length; i++) {
str = str +a[i];
}
return Long.parseLong(str);
}
public static void swap(int a[],int i,int j){
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}