Accepted C Solution,any suggestions?


  • 0
    X

    char** summaryRanges(int* nums, int numsSize, int* returnSize) {

    int numstmp[numsSize+1];
    int start = 0;
    int k = 0;
    
    char **res = (char**)malloc(sizeof(char*)*numsSize);
    if(numsSize<1)
        return res;
    for(int i = 0;i < numsSize;i++)
        numstmp[i] = nums[i];
    numstmp[numsSize] = nums[numsSize-1];
    for(int j = 0;j<numsSize;j++)
    {
        if(numstmp[j]-numstmp[j+1] != -1)
        {                
            
            char *str = (char*)malloc(100);
            sprintf(str,"%d",numstmp[start]);
            res[k] = str;
            if(j - start >0)
                {
                    sprintf(str,"%d->%d",numstmp[start],numstmp[j]);
                    res[k] = str;                 
                }
            start = j+1;
            k++;
        }
    }
    *returnSize = k;
    return res;
    

    }


  • 0
    G

    You could use less memory for "res" and each of the strings, and only allocate what you need. Also, you can use less memory by not using a copy of "nums", i.e. "numstmp".


Log in to reply
 

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