开发一个网站能赚多少钱,宝安中心区规划,网页设计如何在图片上添加文字,代运营主要做什么题目描述
以数组 intervals 表示若干个区间的集合#xff0c;其中单个区间为 intervals[i] [start_i, end_i] 。请你合并所有重叠的区间#xff0c;并返回 一个不重叠的区间数组#xff0c;该数组需恰好覆盖输入中的所有区间 。
示例 1#xff1a;
输入#xff1a;int…题目描述
以数组 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
}