【Leetcode】 C语言 228. Summary Ranges
作者:互联网
- Summary Ranges
题目分析:输出数组的连续排序的数字,如果有数字断档就再分接上后续的范围。利用两个指针分别指向连续的两个数字判断是否相差+1,再循环。
char ** summaryRanges(int* nums, int numsSize, int* returnSize){
char **ret = malloc(sizeof(char*)*20);
*returnSize = 0;
if(numsSize == 0){
return NULL;
}
if(numsSize == 1){
ret[0]=calloc(10,sizeof(char));
sprintf(ret[0],"%d",nums[0]);
*returnSize = 1;
return ret;
}
int i,init=nums[0],curr=nums[0];
for(i=0;i<numsSize-1;i++){
curr=nums[i];
if(curr+1!=nums[i+1]){
if(curr != init){
ret[*returnSize]=calloc(30,sizeof(char));
sprintf(ret[*returnSize],"%d->%d",init,nums[i]);
*returnSize += 1;
}
else{
ret[*returnSize]=calloc(20,sizeof(char));
sprintf(ret[*returnSize],"%d",nums[i]);
*returnSize += 1;
}
init=nums[i+1];
}
}
if(nums[numsSize-2]+1 == nums[numsSize-1]){
ret[*returnSize]=calloc(30,sizeof(char));
sprintf(ret[*returnSize],"%d->%d",init,nums[i]);
*returnSize += 1;
}
else{
ret[*returnSize]=calloc(20,sizeof(char));
sprintf(ret[*returnSize],"%d",nums[i]);
*returnSize += 1;
}
return ret;
}
标签:char,returnSize,nums,ret,Summary,Ranges,init,228,sizeof 来源: https://blog.csdn.net/LYYF177/article/details/123191730