给定一组非负整数,重新排列它们的顺序使之组成一个最大的整数。
示例 1:
输入: [10,2]
输出: 210
示例 2:
输入: [3,30,34,5,9]
输出: 9534330
说明: 输出结果可能非常大,所以你需要返回一个字符串而不是整数。
解法1:
public String largestNumber(int[] nums) {
quickSort(nums, 0, nums.length - 1);
StringBuilder sb = new StringBuilder();
for(int i:nums){
sb.append(i+"");
}
return sb.toString().charAt(0)=='0'?"0":sb.toString();
}
public void quickSort(int nums[],int l,int r){
if(l>=r)
return;
int key = nums[l];
int i = l;
int j = r;
while(i<j){
while(i<j&&isLarge(key,nums[j])){
j--;
}
while(i<j&&isLarge(nums[i],key)){
i++;
}
if(i<j){
int tem = nums[i];
nums[i] = nums[j];
nums[j] = tem;
}
}
nums[l] = nums[i];
nums[i] = key;
quickSort(nums,l,i-1);
quickSort(nums,i+1,r);
}
public boolean isLarge(int i,int j){
if(i==j)
return true;
String a = String.valueOf(i);
String b = String.valueOf(j);
for(int k=0;k<=Math.max(a.length(),b.length());k++){
if(a.charAt(k%a.length())==b.charAt(k%b.length())){
continue;
}else {
return a.charAt(k%a.length())>b.charAt(k%b.length());
}
}
return true;
}
解法2:
public String largestNumber(int[] nums) {
String str[] = new String[nums.length];
for(int i=0;i<nums.length;i++){
str[i] = String.valueOf(nums[i]);
}
Arrays.sort(str, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
String s1 = o1+o2;
String s2 = o2+o1;
return s2.compareTo(s1);
}
});
StringBuilder sb = new StringBuilder();
for(String s:str){
sb.append(s);
}
return sb.toString().charAt(0)=='0'?"0":sb.toString();
}