代码实现:
/** * Note: The returned array must be malloced, assume caller calls free(). */ char** summaryRanges(int* nums, int numsSize, int *returnSize) { char **res = malloc(sizeof(char*) * numsSize); *returnSize = 0; int i, j; for (i = 0; i < numsSize; i++) { // i: 区间左边第一个 for (j = i + 1; j < numsSize; j++) { // j-1:区间右边第一个 if (nums[j] != nums[j - 1] + 1) { break; } } // [i...j-1] char *ret = malloc(sizeof(char) * (25)); sprintf(ret, "%d", nums[i]); if (i != j - 1) { sprintf(ret + strlen(ret), "->"); sprintf(ret + strlen(ret), "%d", nums[j - 1]); } ret[strlen(ret)] = '\0'; res[(*returnSize)++] = ret; i = j - 1; } return res; }