给定一个排序的整数数组 nums ,其中元素的范围在 闭区间 [lower, upper] 当中,返回不包含在数组中的缺失区间。
示例:
输入: nums = [0, 1, 3, 50, 75], lower = 0 和 upper = 99,
输出: ["2", "4->49", "51->74", "76->99"]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/missing-ranges
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
char *int_to_str(int val)
{
int len=1;
int tmp=val/10;
while(tmp!=0)
{
len++;
tmp=tmp/10;
}
if(val<0)len++;
char *ret=(char *)malloc(sizeof(char)*(len+1));
sprintf(ret,"%d",val);
return ret;
}
char *add_int_to_str(char *str,int val)
{
int len=1;
int len1=strlen(str);
int tmp=val/10;
while(tmp!=0)
{
len++;
tmp=tmp/10;
}
if(val<0)len++;
len+=len1+2;
str=(char *)realloc(str,sizeof(char)*(len+1));
sprintf(str+len1,"->%d",val);
return str;
}
char ** findMissingRanges(int* nums, int numsSize, int lower, int upper, int* returnSize){
char **ret=NULL;
* returnSize=0;
int pos=0;
bool finished=false;
while(pos<numsSize)
{
if(nums[pos]<lower)
{//去除重复数字
pos++;
continue;
}
if(nums[pos]==lower)
{
if(lower!=INT_MAX)lower++;
else
{
finished=true;
break;
}
pos++;
}
else
{
(* returnSize)++;
ret=(char **)realloc(ret,sizeof(char *)*(* returnSize));
ret[(* returnSize)-1]=int_to_str(lower);
if(nums[pos]!=lower+1)
{
ret[(* returnSize)-1]=add_int_to_str(ret[(* returnSize)-1],nums[pos]-1);
}
if(nums[pos]!=INT_MAX)lower=nums[pos]+1;
else
{
finished=true;
break;
}
pos++;
}
}
if(!finished&&lower==upper)
{
(* returnSize)++;
ret=(char **)realloc(ret,sizeof(char *)*(* returnSize));
ret[(* returnSize)-1]=int_to_str(lower);
}
else if(!finished&&lower<upper)
{
(* returnSize)++;
ret=(char **)realloc(ret,sizeof(char *)*(* returnSize));
ret[(* returnSize)-1]=int_to_str(lower);
ret[(* returnSize)-1]=add_int_to_str(ret[(* returnSize)-1],upper);
}
else
{
printf("finished!\n");
}
return ret;
}
执行用时 :0 ms, 在所有 C 提交中击败了100.00% 的用户
内存消耗 :6.8 MB, 在所有 C 提交中击败了100.00%的用户