题解 | #合并区间#
合并区间
http://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a
int comp(const void *a,const void *b)
{
if((*(struct Interval*)a).start!=(*(struct Interval*)b).start)
return (*(struct Interval*)a).start-(*(struct Interval*)b).start;
else
return (*(struct Interval*)a).end-(*(struct Interval*)b).end;
}
struct Interval* merge(struct Interval* intervals, int intervalsLen, int* returnSize )
{
qsort(intervals, intervalsLen, sizeof(struct Interval), comp);
int len=intervalsLen;
struct Interval* res= malloc(sizeof(struct Interval)*intervalsLen);
int j=0;
for(int i=0;i<intervalsLen;)
{
int start1=intervals[i].start;
int end1=intervals[i].end;
while(end1>=intervals[i+1].start)
{ if(end1<=intervals[i+1].end)
end1=intervals[i+1].end;
i++;
}
res[j].start=start1;
res[j].end=end1;
j++;
i++;
}
*returnSize=j;
return res;
}
{
if((*(struct Interval*)a).start!=(*(struct Interval*)b).start)
return (*(struct Interval*)a).start-(*(struct Interval*)b).start;
else
return (*(struct Interval*)a).end-(*(struct Interval*)b).end;
}
struct Interval* merge(struct Interval* intervals, int intervalsLen, int* returnSize )
{
qsort(intervals, intervalsLen, sizeof(struct Interval), comp);
int len=intervalsLen;
struct Interval* res= malloc(sizeof(struct Interval)*intervalsLen);
int j=0;
for(int i=0;i<intervalsLen;)
{
int start1=intervals[i].start;
int end1=intervals[i].end;
while(end1>=intervals[i+1].start)
{ if(end1<=intervals[i+1].end)
end1=intervals[i+1].end;
i++;
}
res[j].start=start1;
res[j].end=end1;
j++;
i++;
}
*returnSize=j;
return res;
}