Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3], [2,6], [8,10], [15,18],
return [1,6], [8,10], [15,18].
思路:本题的难度虽然是hard,但是实际上比较简单,就是先排序,后合并。下面的代码使用了realloc(584 ms),如果直接使用malloc分配足够的内存,结果竟然会变慢(692 ms),呵呵。代码如下:
struct Interval { int start; int end; }; int compar(constvoid *a, const void *b) { return ((struct Interval *)a)->start- ((struct Interval *)b)->start; } struct Interval*merge(struct Interval* intervals, int intervalsSize,int* returnSize) { int i; int laststart, lastend; struct Interval *res = NULL; int reslen = 0; if(intervalsSize == 0) return res; qsort(intervals, intervalsSize,sizeof(struct Interval), compar); laststart = intervals[0].start; lastend = intervals[0].end; for(i = 1; i <intervalsSize; i++) { if(intervals[i].start<= lastend) { if(lastend < intervals[i].end) { lastend = intervals[i].end; } } else { reslen++; res = realloc(res,reslen*sizeof(struct Interval)); res[reslen-1].start= laststart; res[reslen-1].end= lastend; laststart = intervals[i].start; lastend = intervals[i].end; } } reslen++; res = realloc(res, reslen*sizeof(structInterval)); res[reslen-1].start =laststart; res[reslen-1].end =lastend; *returnSize = reslen; return res; }