179 Largest Number
链接:https://leetcode.com/problems/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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Hide Tags Sort
这个问题是求一个数组中数字可以组成的的最大数字是多少。如何确定两个数字谁在前谁在后呢?假设a,b两个数字,ab>=ba,那么a应该在前,b应该在后,比如3和30,330>=303,所以应该3在30前面。这里以此为依据建立比较两个数字大小的规则:如果ab>=ba,则a>b。以此为规则,将给出的数组排序,数组排序后移动到字符数组就可以得到结果。考虑到排序的效率,我在写排序的时候用了快速排序。
bool compare(int a,int b)
{
int al=0,bl=0,ta=a,tb=b;
if(a==0) al=1;
if(b==0) bl=1;
while(ta>0)
{
ta/=10;
al++;
}
while(tb>0)
{
tb/=10;
bl++;
}
if(pow(10,al)*b+a>pow(10,bl)*a+b)
return false;
return true;
}
void msort(int *a,int size)
{
if(size<=1) return ;
int key=a[0],i=1,j=size-1;
while(i!=j)
{
while(compare(key,a[j])&&j>i)
j--;
while(compare(a[i],key)&&i<j)
i++;
if(i==j)
{
break;
}
else
{
int k=a[i];
a[i]=a[j];
a[j]=k;
}
}
if(compare(a[j],key))
{
a[0]=a[i];
a[i]=key;
}
msort(a,i);
msort(a+i,size-i);
}
char* largestNumber(int* nums, int numsSize)
{
int length=0;
char* result;
if(numsSize==0) return result;
for(int i=0;i<numsSize;i++)
{
int k=nums[i];
if(k==0) length++;
while(k>0)
{
length++;
k/=10;
}
}
result=(char*)malloc(sizeof(char)*(length+1));
result[length]='\0';
length=0;
msort(nums,numsSize);
for(int i=0;i<numsSize;i++)
{
int k=nums[i];
int il=0;
if(k==0)
{
result[length++]=0+'0';
}
while(k>0)
{
result[length++]=k%10+'0';
il++;
k/=10;
}
for(int k=0;k<il/2;k++)
{
char t=result[length-il+k];
result[length-il+k]=result[length-k-1];
result[length-k-1]=t;
}
}
if(result[0]=='0')
{
free(result);
char *r=(char *)malloc(2);
r[0]='0';
r[1]='\0';
return r;
}
return result;
}