【leetcode】179. 最大数

 

int cmp(const void*a,const void*b){
    char s1[100],s2[100];
    sprintf(s1,"%d%d",*(int *)a,*(int *)b);
    sprintf(s2,"%d%d",*(int *)b,*(int *)a);
    return strcmp(s2,s1);
}
char * largestNumber(int* nums, int numsSize){
    qsort(nums,numsSize,sizeof(int),cmp);
    if(nums[0]==0) 
        return "0";
    char* res=(char*)calloc(sizeof(char),1000);
    int i,len=0;
    for(i=0;i<numsSize;i++){
        len+= sprintf(res+len,"%d",nums[i]);
    }
    return res;
}

 

int cmp(const void* a,const void* b){
    char* s1=(*(char**)a);
    char* s2=(*(char**)b);
    int i;
    for (i=0; s1[i] && s2[i]; i++ )
    {
        if(s1[i] != s2[i])
            return s1[i]<s2[i];
    }
    if(s1[i] == '\0' && s2[i] == '\0')
        return 0;
    else if(s2[i] == '\0'){
        char* buffer=(char*)calloc(20,sizeof(char));
        strcat(buffer,s1+i);
        strcat(buffer,s2);
        return strcmp(s1,buffer);
    }
    else if(s1[i] == '\0'){        
        char* buffer=(char*)calloc(20,sizeof(char));
        strcat(buffer,s2+i);
        strcat(buffer,s1);    
        return strcmp(buffer,s2);
    }
    return 0;
}
char * largestNumber(int* nums, int numsSize){
    char** arr=(char**)calloc(numsSize,sizeof(char*));
    char* retStr=(char*)calloc(500,sizeof(char));
    int i;
    for (i=0; i<numsSize; i++)
    {
        char* temp=(char*)calloc(20,sizeof(char));
        sprintf(temp,"%d",nums[i]);
        arr[i]=temp;
        
    }
    qsort(arr,numsSize,sizeof(char*),cmp);  
    for (i=0; i<numsSize; i++)
        strcat(retStr,arr[i]);
    return (*retStr=='0')?"0" :retStr;
}

 

posted @ 2020-12-24 17:47  温暖了寂寞  阅读(94)  评论(0编辑  收藏  举报