题解 | #合并区间#
合并区间
https://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a
/** * struct Interval { * int start; * int end; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param intervals Interval类一维数组 * @param intervalsLen int intervals数组长度 * @return Interval类一维数组 * @return int* returnSize 返回数组行数 */ #define max(a,b) a>b?a:b int compare(const void* a, const void* b) { struct Interval *A = (struct Interval*)a; struct Interval *B = (struct Interval*)b; return A->start - B->start; } struct Interval* merge(struct Interval* intervals, int intervalsLen, int* returnSize ) { // write code here if (intervalsLen == 1) { *returnSize = 1; return intervals; } qsort(intervals, intervalsLen, sizeof(struct Interval), compare); for(int i = 0; i < intervalsLen; i++) { printf("start:intervals[%d].start%d\nend:intervals[%d].end%d\n",i,intervals[i].start,i,intervals[i].end); } *returnSize = 0; struct Interval * result = (struct Interval*)malloc(sizeof(struct Interval) * intervalsLen); int idx = 0; while(idx < intervalsLen) { struct Interval new; new.start = intervals[idx].start; new.end = intervals[idx].end; idx++; while(idx < intervalsLen && new.end >= intervals[idx].start) { printf("max of %d and %d is %d\n",new.end, intervals[idx].end, max(new.end, intervals[idx].end)); new.end = max(new.end, intervals[idx].end); idx++; } result[(*returnSize)] = new; (*returnSize)++; } return result; }