题目描述
以数组 intervals
表示若干个区间的集合,其中单个区间为 intervals[i] = [start_i, end_i]
。请你合并所有重叠的区间,并返回 一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间 。
示例 1:
输入:intervals = [[1,3],[2,6],[8,10],[15,18]]
输出:[[1,6],[8,10],[15,18]]
解释:区间 [1,3]
和 [2,6]
重叠, 将它们合并为 [1,6]
.
示例 2:
输入:intervals = [[1,4],[4,5]]
输出:[[1,5]]
解释:区间 [1,4]
和 [4,5]
可被视为重叠区间。
提示:
1 <= intervals.length <= 10^4
intervals[i].length == 2
0 <= start_i <= end_i <= 10^4
题解:排序
思路
如果我们按照区间的左端点排序,那么在排完序的列表中,可以合并的区间一定是连续的。如下图所示,标记为蓝色、黄色和绿色的区间分别可以合并成一个大区间,它们在排完序的列表中是连续的:
算法
我们用数组 merged
存储最终的答案。
首先,我们将列表中的区间按照左端点升序排序。然后我们将第一个区间加入 merged
数组中,并按顺序依次考虑之后的每个区间:
如果当前区间的左端点在数组 merged
中最后一个区间的右端点之后,那么它们不会重合,我们可以直接将这个区间加入数组 merged
的末尾;
否则,它们重合,我们需要用当前区间的右端点更新数组 merged
中最后一个区间的右端点,将其置为二者的较大值。
代码
/*** 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().*/// Function to compare intervals for sorting
int compareIntervals(const void* a, const void* b) {int **arr1 = (int **)a;int **arr2 = (int **)b;// In this line, the function compares the start values of two intervals. // It accesses the first element of the arrays pointed to by arr1 and arr2 , // which corresponds to the start value of the intervals. // By subtracting the start value of the second interval from the start value of the first interval, // the function determines the order in which the intervals should be sorted. return arr1[0][0] - arr2[0][0];
}// Function to merge overlapping intervals
int** merge(int** intervals, int intervalsSize, int* intervalsColSize, int* returnSize, int** returnColumnSizes) {// Check if the input array is emptyif (intervalsSize == 0) {*returnSize = 0;return NULL;}// Sort intervals based on the start valueqsort(intervals, intervalsSize, sizeof(int*), compareIntervals);// Initialize variables for merged intervalsint** merged = (int**)malloc(intervalsSize * sizeof(int*));*returnColumnSizes = (int*)malloc(intervalsSize * sizeof(int));int mergedCount = 0;// Iterate through the sorted intervals to merge overlapping intervalsfor (int i = 0; i < intervalsSize; ++i) {int L = intervals[i][0], R = intervals[i][1];// If the merged array is empty or the current interval does not overlap with the last interval in mergedif (mergedCount == 0 || merged[mergedCount - 1][1] < L) {// Add the current interval to the merged arraymerged[mergedCount] = (int*)malloc(2 * sizeof(int));merged[mergedCount][0] = L;merged[mergedCount][1] = R;(*returnColumnSizes)[mergedCount] = 2;mergedCount++;} else {// Update the end of the last interval in merged if there is an overlapmerged[mergedCount - 1][1] = (R > merged[mergedCount - 1][1]) ? R : merged[mergedCount - 1][1];}}*returnSize = mergedCount; // Set the size of the merged arrayreturn merged; // Return the merged intervals
}