码迷,mamicode.com
首页 > 其他好文 > 详细

Summary Ranges

时间:2015-09-28 14:39:52      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

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;
}

Summary Ranges

标签:

原文地址:http://www.cnblogs.com/dylqt/p/4843902.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!