标签:
Given a sorted integer array without duplicates, return the summary of its ranges.
For example, given [0,1,2,4,5,7]
, return ["0->2","4->5","7"].
将没有重复,已经排好序的数组,返回下面的形式,如果连续就输出头尾的字符串,如果一个就返回一个字符
/** * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */ char *retStr(int start, int end) { char *tmp = malloc(32 * sizeof(char)); //这里注意要大一点,因为如果值太小会存不下 if(start == end) //并且不能定义为数组tmp[32]的形式 sprintf(tmp, "%d", start); //局部变量在返回时会被清空,返回指针也没用 else sprintf(tmp, "%d->%d", start, end); return tmp; } char** summaryRanges(int* nums, int numsSize, int* returnSize) { long start = 0, end = 0; char **result = NULL; if(numsSize == 0) return NULL; start = end = nums[0]; if(numsSize == 1) { result = (char **)realloc(result, (*returnSize + 1) * sizeof(char **)); result[(*returnSize)++] = retStr(start, end); return result; } for(int n = 0; n < numsSize; n++) { if(nums[n + 1] - nums[n] == 1) { end = nums[n + 1]; continue; } else { result = (char **)realloc(result, (*returnSize + 1) * sizeof(char **)); //每次增大空间 result[(*returnSize)++] = retStr(start, end); start = end = nums[n + 1]; } } return result; }
标签:
原文地址:http://www.cnblogs.com/dylqt/p/4843902.html