##问题描述
Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9]
, the largest formed number is 9534330.
Note: The result may be very large, so you need to return a string instead of an integer.
##问题分析
利用JAVA的一些小技巧,重新构造一个操作符,来比较字符串的大小
String的 compareTo 其实就是依次比较两个字符串ASC码。如果两个字符的ASC码相等则继续后续比较,否则直接返回两个ASC的差值。如果两个字符串完全一样,则返回0。来看一下代码
compareTo进行简单 字符串的排序
“abcd”.compareTo(“adef”)== -2
“abc”.compareTo(“abcdef”)== -3
“abc”.compareTo(“abc”) == 0
以下为例子
“930”.compareTo(“309”) = 6 > 0
Arrays.sort():将数组从小到大排列
重新构造操作符,使得从大到小排列数组
##JAVA代码
public class Solution{
class StringComparator implements Comparator
public int compare(String s1,String s2){
String s1s2 = s1 + s2;
String s2s1 = s2 + s1;
//“930”>”309” 返回-1
if(s1s2.compareTo(s2s1) > 0) return -1;
else if (s2s1.compareTo(s1s2) >0) return 1;
else if (s1.length() <= s2.length() ) return -1;
else return 1;
}
}
public String largestNumber(int[] num){
String[] nums = new String[num.length];
for(int i = 0; i < num.length; i++){
nums[i] = String.valueOf(num[i]);
}
Comparator<String> comparator = new StringComparator();
Arrays.sort(nums,comparator);
StringBuilder str = new StringBuilder();
for(String n:nums){
str.append(n);
}
return str.charAt(0)=='0'?"0":str.toString();
}
}