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.
一刷
题解:
首先把int[] 变为String[], 这样遍于sort
sort的原则是,对于String a和b, 如果a+b > b+a, 那么a在前。
然后StringBuilder 逐一append String[]中的元素。
public class Solution {
public String largestNumber(int[] nums) {
if(nums == null || nums.length == 0) return "";
//convert int array to string array
String[] s_num = new String[nums.length];
for(int i=0; i<nums.length; i++){
s_num[i] = String.valueOf(nums[i]);
}
//sort the string according to first character
Arrays.sort(s_num, new Comparator<String>(){
public int compare(String a, String b){
String s1 = a+b;
String s2 = b+a;
return s2.compareTo(s1);//reverse
}
});
if(s_num[0].charAt(0) == '0') return "0";//edge case, the input is a bunch of 0
StringBuilder sb = new StringBuilder();
for(String s: s_num) sb.append(s);
return sb.toString();
}
}
二刷
同一刷
public class Solution {
public String largestNumber(int[] nums) {
if(nums == null || nums.length == 0) return "";
String[] s_num = new String[nums.length];
for(int i=0; i<nums.length; i++){
s_num[i] = String.valueOf(nums[i]);
}
Arrays.sort(s_num, new Comparator<String>(){
public int compare(String a, String b){
String s1 = a+b;
String s2 = b+a;
return s2.compareTo(s1);//reverse
}
});
StringBuilder sb = new StringBuilder();
if(s_num[0].charAt(0) == '0') return "0";
for(String s:s_num){
sb.append(s);
}
return sb.toString();
}
}