2016年2月21日 星期日

LEET code -- Summary Ranges

 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"].


用指標   要小心16行   50那邊不能給太小


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
char** summaryRanges(int* nums, int numsSize, int* returnSize) {
    *returnSize=0;
    if(!nums)return NULL;
    int size=20;
    char **ans = calloc(size,sizeof(char*));
    int *start=nums,*next=nums;
    //int start=0,next=0;
    
    while((next-nums)<numsSize){
        //printf("%d %d\n",*next,nums[0]);
        while(*(next+1) && *next==*(next+1)-1 ){next++; printf("TT%d\n",*next);}
        char *temp=calloc((next-start+1)*50,sizeof(char));
        temp[0]='\0';
        if(*next==*start)sprintf(temp,"%d\0",*next);
        else sprintf(temp,"%d->%d\0",*start,*next);
        //for(int i=0;i<(next-start);i++,start++)sprintf(temp,"%s%d->",temp,*start);//wrong this printt all range
        //sprintf(temp,"%s%d",temp,*next);
        ans[*returnSize]=temp;
        printf("%s\n",temp);
        *returnSize+=1;
        if(*returnSize > size*0.7){
            ans=realloc(ans,sizeof(char *)*size*2);
            size*=2;
        }
        next++;
        start=next;
        
    }
    return ans;
}




------------
C++



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        int size=nums.size();
        vector<string> ans;
        if(size==0)return ans;
        for(int i=0;i<size;){
            int start=i,end=i;
            while(end+1<size && nums[end]==nums[end+1]-1 )end++;
            if(start==end)ans.push_back(to_string(nums[start]));
            else ans.push_back(to_string(nums[start])+"->"+to_string(nums[end]));
            i=end+1;
        }
        return ans;
    }
    
};

沒有留言:

張貼留言