问题描述
(1) Largest Number. 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.
思路
首先需要对原来的数组进行特殊排序,对于小于10的数字直接进行比较,而大于10 的数字需要进行处理,首先比较首位数字大小,如30和444,取得首位3和4,判断4>3,还有一种情况是例如30和3,若第一位数字相同,则比较第二位的数字0和3,很明显0要小于3,因此这里3>30。然后按照这个排序方法对原数组进行排序的同时,引入StringBuilder变量进行拼接。
代码
public static StringBuilder getMaxInteger(int [] nums){
StringBuilder builder = new StringBuilder();
cut( nums, builder);
return builder;
}
public static int [] cut(int [] nums,StringBuilder stringBuilder){
if(nums.length < 2){
return nums;
}
int half = nums.length >> 1;
int[] left = Arrays.copyOfRange(nums, 0, half);
int[] right = Arrays.copyOfRange(nums, half, nums.length);
return merge(cut(left,stringBuilder),cut(right,stringBuilder),stringBuilder);
}
public static int [] merge(int [] left,int [] right,StringBuilder stringBuilder){
int l = 0;
int r = 0;
int lTemp = left[l];
int rTemp = right[r];
stringBuilder.delete(0, stringBuilder.length());
int [] result = new int[left.length+right.length];
for (int i = 0; i < result.length; i++) {
if(l >= left.length){
result[i] = right[r++];
stringBuilder.append(result[i]);
}else if( r >= right.length){
result[i] = left[l++];
stringBuilder.append(result[i]);
}else if(isOverTen(left[l],lTemp,right[r],rTemp)){
result[i] = left[l++];
stringBuilder.append(result[i]);
}else{
result[i] = right[r++];
stringBuilder.append(result[i]);
}
}
return result;
}
public static boolean isOverTen(int num1,int temp1,int num2,int temp2){
if(temp1 < 10){
if(temp2 < 10){
if(temp1 > temp2){
return true;
}else if(temp1 == temp2 && num2 >= 10){
temp2 = num2 % 10;
return isOverTen( num1, temp1, num2, temp2);
}else {
return false;
}
}else{
temp2 /= 10;
return isOverTen( num1, temp1, num2, temp2);
}
}
temp1 /= 10;
if(temp1 == temp2 && num1 >= 10){
temp1 = num1 % 10;
return isOverTen( num1, temp1, num2, temp2);
}
return isOverTen( num1, temp1, num2, temp2);
}