代码实现:
解题思路:先将数组 newInterval 插入到数组 intervals 的末尾,再转换成合并区间
/** * Return an array of arrays of size *returnSize. * The sizes of the arrays are returned as *returnColumnSizes array. * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). */ // 交换 void swap(int *m, int *n) { int temp = *m; *m = *n; *n = temp; } // 快排 void sort(int (*nums)[2], int l, int r) { // 左闭右开 if (r - l <= 2) { if (r - l <= 1) { // 剩余个数:<= 1 return; } if (nums[r - 1][0] < nums[l][0]) { // 剩余个数:= 2 且后者小于前者 交换 swap(&nums[r - 1][0], &nums[l][0]); swap(&nums[r - 1][1], &nums[l][1]); } return; } int x = nums[l][0]; int y = nums[l][1]; int i = l, j = r - 1; while (i < j) { while (i < j && nums[j][0] >= x) { j--; } if (i < j) { nums[i][0] = nums[j][0]; nums[i][1] = nums[j][1]; i++; } while (i < j && nums[i][0] <= x) { i++; } if (i < j) { nums[j][0] = nums[i][0]; nums[j][1] = nums[i][1]; j--; } } nums[i][0] = x, nums[i][1] = y; sort(nums, l, i); sort(nums, i + 1, r); } int** insert(int **intervals, int intervalsSize, int *intervalsColSize, int *newInterval, int newIntervalSize, int *returnSize, int **returnColumnSizes) { int ret[intervalsSize + 1][2]; for (int i = 0; i < intervalsSize; i++) { ret[i][0] = intervals[i][0]; ret[i][1] = intervals[i][1]; } ret[intervalsSize][0] = newInterval[0]; ret[intervalsSize][1] = newInterval[1]; int retSize = intervalsSize + 1; // 合并区间 *returnSize = 0; // 按左边界(从小到大)快排 sort(ret, 0, retSize); // 左闭右开 *returnColumnSizes = malloc(sizeof(int) * retSize); int **result = malloc(sizeof(int*) * retSize); // 记录结果 int left = ret[0][0]; int right = ret[0][1]; for (int i = 1; i < retSize; i++) { if (right >= ret[i][0]) { right = right > ret[i][1] ? right : ret[i][1]; } else { (*returnColumnSizes)[(*returnSize)] = 2; result[(*returnSize)] = malloc(sizeof(int) * 2); result[(*returnSize)][0] = left; result[(*returnSize)][1] = right; (*returnSize)++; left = ret[i][0]; right = ret[i][1]; } } // 记录合并的最后一个区间 (*returnColumnSizes)[(*returnSize)] = 2; result[(*returnSize)] = malloc(sizeof(int) * 2); result[(*returnSize)][0] = left; result[(*returnSize)][1] = right; (*returnSize)++; return result; }