0ms C solution with no memory waste


  • 0
    G
    char** summaryRanges(int* nums, int numsSize, int* returnSize) {
        *returnSize = 0;
        char **ret = NULL;
        
        int *p = nums, *q = nums+1;
        int temp;
        while (p && p < nums + numsSize) {
            temp = *p;
            while(q < nums + numsSize && *q==temp+1){
                temp = *q;
                q++;
            }
            // summarize p...q-1
            *returnSize = *returnSize + 1;
            ret = (char **) realloc(ret, sizeof(char *) * (*returnSize));
            ret[(*returnSize)-1] = (char*) malloc(100);
            if (p + 1 == q){
                // only one number
                asprintf(ret+(*returnSize)-1, "%d", *p);
            } else {
                // more than one number
                asprintf(ret+(*returnSize)-1, "%d->%d", *p, *(q-1));
            }
            // move forward
            p = q;
            q++;
        }
        
        return ret;
    }

Log in to reply
 

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