56.merge intervals
56.merge intervals Given a collection of intervals, merge all overlapping intervals. Example 1: Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. Example 2: Input: [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considerred overlapping.
// 4ms #include <stdio.h> #include <stdlib.h> #include <math.h> #include <limits.h> //Definition for an interval. struct Interval { int start; int end; }; int comp(const void *x, const void *y) { struct Interval a = *(struct Interval *)x; struct Interval b = *(struct Interval *)y; // ASC return a.start - b.start; } /** * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */ struct Interval* merge(struct Interval* intervals, int intervalsSize, int* returnSize) { if(intervalsSize == 0) return intervals; struct Interval *result = (struct Interval *)malloc(sizeof(struct Interval) * intervalsSize); qsort(intervals, intervalsSize, sizeof(struct Interval), comp); *returnSize = 0; result[0].start = intervals[0].start; result[0].end = intervals[0].end; for (int i = 1; i < intervalsSize; ++i) { if(result[*returnSize].end < intervals[i].start) { ++*returnSize; result[*returnSize].start = intervals[i].start; result[*returnSize].end = intervals[i].end; }else if (result[*returnSize].end < intervals[i].end) { result[*returnSize].end = intervals[i].end; } //(result[*returnSize].end >= intervals[i].end) } ++*returnSize; return result; }