Largest Number

来源:互联网 发布:adb devices 端口 编辑:程序博客网 时间:2024/06/16 21:24

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.

解题思路:
(1)将整型数组转换成字符串数组
(2)对字符串数组按照递减的顺序进行希尔排序
(3)将排序后的字符串用strcat()函数拼接起来

char* largestNumber(int* nums, int numsSize) {

//将整型数组转换成字符串数组char** strNums = (char**)malloc(sizeof(int*)*numsSize);for (int i = 0; i < numsSize; i++){    strNums[i] = (char*)malloc(sizeof(char)*10);    sprintf(strNums[i],"%d",nums[i]);}//对字符串数组进行希尔排序,按递减的顺序,判断条件与常规的排序有点不同for (int Incre = numsSize/2; Incre > 0; Incre /= 2){    for (int i = Incre; i < numsSize; i++)    {        int j;        char temp[10];        strcpy(temp, strNums[i]);        for (j = i; j >= Incre; j -= Incre)        {            char str1[20] = {'\0'};            char str2[20] = {'\0'};            sprintf(str1, "%s%s",temp,strNums[j-Incre]);            sprintf(str2, "%s%s",strNums[j-Incre],temp);            if (strcmp(str1,str2) > 0)                strcpy(strNums[j],strNums[j-Incre]);            else                break;        }        strcpy(strNums[j],temp);    }}//判断数组是不是全部为0if (strcmp(strNums[0],"0") == 0)    return "0";//将排序后的数组合并成字符串char* res = (char*)malloc(sizeof(char)*numsSize*10);memset(res,'\0',strlen(res));for (int i = 0; i < numsSize; i++)    strcat(res,strNums[i]);for (int i = 0; i < numsSize; i++)    free(strNums[i]);free(strNums);return res;

}

0 0
原创粉丝点击