https://www.nowcoder.com/questionTerminal/8fecd3f8ba334add803bf2a06af1b993
描述
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
解析
两个数互相加起来,比较。
代码
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Solution { public String PrintMinNumber(int [] numbers) { if (null == numbers || numbers.length <= 0) { return ""; } Comparator<Integer> comparator = new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { StringBuffer sb = new StringBuffer(); sb.append(o1); sb.append(o2); StringBuffer sb1 = new StringBuffer(); sb1.append(o2); sb1.append(o1); return sb.toString().compareTo(sb1.toString()); } }; List<Integer> list = new ArrayList<>(numbers.length); for (int i = 0; i < numbers.length; i++) { list.add(numbers[i]); } Collections.sort(list, comparator); StringBuffer sb = new StringBuffer(); for (int i = 0; i < list.size(); i++) { sb.append(list.get(i)); } return sb.toString(); } }