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,a和b,a在前大还是b在前大。
刚开始想复杂了,比较准则还想着按位来,居然也A掉了,然而其中的原理仍然感觉似乎不是那么站得住脚?
public String largestNumber(int[] nums)
{
StringBuilder sb=new StringBuilder();
int len=nums.length;
Integer[] arr=new Integer[len];
for(int i=0;i<len;i++)
arr[i]=Integer.valueOf(nums[i]);
Arrays.sort(arr, new mycomparator2());
for(int i=len-1;i>=0;i--)
sb.append(arr[i]);
return new java.math.BigInteger(sb.toString()).toString();
}
class mycomparator2 implements Comparator<Object>
{
public int compare(Object o1, Object o2)
{
Integer io1=(Integer) o1;
Integer io2=(Integer) o2;
/*
String s1=io1.toString();
String s2=io2.toString();
long cmp=Long.parseLong(s1+s2)-Long.parseLong(s2+s1);
if(cmp>0)
return 1;
else if(cmp<0)
return -1;
return 0;
*/
if(io1==2&&io2==2281)
{
System.out.println();
}
if(io1==0&&io2>0)
return -1;
else if(io1!=0&&io2==0)
return 1;
else if(io1==0&&io2==0)
return 0;
int cnt1=0;
int cnt2=0;
int[] bit1=new int[10];
int[] bit2=new int[10];
while(io1>0)
{
bit1[cnt1++]=io1%10;
io1/=10;
}
while(io2>0)
{
bit2[cnt2++]=io2%10;
io2/=10;
}
cnt1--;
cnt2--;
int cnt1cpy=cnt1;
int cnt2cpy=cnt2;
while(cnt1>=0&&cnt2>=0)
{
if(bit1[cnt1]>bit2[cnt2])
return 1;
else if(bit1[cnt1]<bit2[cnt2])
return -1;
else {
cnt1--;
cnt2--;
}
}
if(cnt1!=cnt2)
{
if(cnt1<0)
{
while(cnt2>=0)
{
cnt1=cnt1cpy;
while(cnt1>=0)
{
if(bit2[cnt2]<bit1[cnt1])
return 1;
else if(bit2[cnt2]>bit1[cnt1])
return -1;
cnt1--;
}
cnt2--;
}
}
else if(cnt2<0)
{
while(cnt1>=0)
{
cnt2=cnt2cpy;
while(cnt2>=0)
{
if(bit1[cnt1]>bit2[cnt2])
return 1;
else if(bit1[cnt1]<bit2[cnt2])
return -1;
cnt2--;
}
cnt1--;
}
}
}
return 0;
}
}
----------------------------------------------------------------------------------
public class Solution {
public String largestNumber(int[] nums)
{
int len=nums.length;
quick_sort(nums,0,len-1);
StringBuilder sb=new StringBuilder();
for(int i=len-1;i>=0;i--)
sb.append(nums[i]);
if(sb.length()>0&&sb.charAt(0)=='0')
return "0";
return sb.toString();
}
public int compare(int o1, int o2)
{
String s1=String.valueOf(o1);
String s2=String.valueOf(o2);
long cmp=Long.parseLong(s1+s2)-Long.parseLong(s2+s1);
if(cmp>0)
return 1;
else if(cmp<0)
return -1;
return 0;
}
private int partition(int[] a,int lo ,int hi)
{
int i=lo;
int j=hi+1;
int v=a[lo];
while(true)
{
while(compare(a[++i], v)<0)
if(i==hi)
break;
while(compare(v, a[--j])<0)
if(j==lo)
break;
if(i>=j)
break;
swap(a, i, j);
}
swap(a, lo, j);
return j;
}
public void quick_sort(int[] a,int lo,int hi)
{
if(hi<=lo)
return ;
int j=partition(a, lo, hi);
quick_sort(a, lo, j-1);
quick_sort(a, j+1, hi);
}
public void swap(int[] a,int i,int j)
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}