Simple C solution 6ms without string compare


  • 0
    K

    Let me know how I can improve the performance from 6ms.

    inline int get_numDigits(int num){
        if(num == 0)
            return 1;
        return ceil(log10(num+1));
    }
    
    int compare(const int* p_num1, const int* p_num2){
        
        int num1_digit_len = get_numDigits(*p_num1);
        int num2_digit_len = get_numDigits(*p_num2);
        
        int num1 = *p_num1;
        int num2 = *p_num2;
        
        //sort in decending order and hence (num2 * something) - (num1 * something)
        return (num2 * (pow(10,num1_digit_len)) + num1) - (num1 * (pow(10,num2_digit_len)) + num2); 
    }
    
    char* largestNumber(int* nums, int numsSize){
        //sort the array using the custom compare function
        qsort(nums, numsSize, sizeof(int), compare);
        uint32_t strLen = 0;
        
        /*Allocate op buffer*/
        for(int i=0; i<numsSize; i++){
            strLen = strLen + get_numDigits(nums[i]); // accumulate the string len needed to malloc
        }
        char* retString = malloc((sizeof(char)*strLen) + 1);
        /* */
        
        /* Run through the array to make the buffer */
        int lenSoFar = 0;
        for(int i=0; i<numsSize; i++){
            lenSoFar += sprintf((retString + lenSoFar), "%d",nums[i]);
            printf("%s\n", retString);
        }
        /* */
        
        if(retString[0] == '0')
            retString[1] = '\0';
        
        return retString;
    }
    

  • 0
    S
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.