当前位置:网站首页>57. insert interval

57. insert interval

2022-06-25 07:52:00 Mr Gao

57. Insert interval

To give you one Without overlap , A list of intervals sorted by their starting and ending points .

Insert a new interval in the list , You need to make sure that the intervals in the list are still ordered and do not overlap ( If necessary , You can merge ranges ).

Example 1:

Input :intervals = [[1,3],[6,9]], newInterval = [2,5]
Output :[[1,5],[6,9]]

Example 2:

Input :intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output :[[1,2],[3,10],[12,16]]
explain : This is because of the new range [4,8] And [3,5],[6,7],[8,10] overlap .

Example 3:

Input :intervals = [], newInterval = [5,7]
Output :[[5,7]]

Example 4:

Input :intervals = [[1,5]], newInterval = [2,3]
Output :[[1,5]]

Example 5:

Input :intervals = [[1,5]], newInterval = [2,7]
Output :[[1,7]]

int** insert(int** intervals, int intervalsSize, int* intervalsColSize, int* newInterval, int newIntervalSize, int* returnSize, int** returnColumnSizes) {
    
    *returnSize = 0;
    int left = newInterval[0];
    int right = newInterval[1];
    bool placed = false;
    int** ans = malloc(sizeof(int*) * (intervalsSize + 1));
    *returnColumnSizes = malloc(sizeof(int*) * (intervalsSize + 1));
    for (int i = 0; i < intervalsSize; ++i) {
    
        int* interval = intervals[i];
        if (interval[0] > right) {
    
            //  On the right side of the insertion interval and without intersection 
            if (!placed) {
    
                int* tmp = malloc(sizeof(int) * 2);
                tmp[0] = left, tmp[1] = right;
                (*returnColumnSizes)[*returnSize] = 2;
                ans[(*returnSize)++] = tmp;
                placed = true;
            }
            int* tmp = malloc(sizeof(int) * 2);
            memcpy(tmp, interval, sizeof(int) * 2);
            (*returnColumnSizes)[*returnSize] = 2;
            ans[(*returnSize)++] = tmp;
        } else if (interval[1] < left) {
    
            //  On the left side of the insertion interval and without intersection 
            int* tmp = malloc(sizeof(int) * 2);
            memcpy(tmp, interval, sizeof(int) * 2);
            (*returnColumnSizes)[*returnSize] = 2;
            ans[(*returnSize)++] = tmp;
        } else {
    
            //  There is an intersection with the insertion interval , Compute their union 
            left = fmin(left, interval[0]);
            right = fmax(right, interval[1]);
        }
    }
    if (!placed) {
    
        int* tmp = malloc(sizeof(int) * 2);
        tmp[0] = left, tmp[1] = right;
        (*returnColumnSizes)[*returnSize] = 2;
        ans[(*returnSize)++] = tmp;
    }
    return ans;
}



原网站

版权声明
本文为[Mr Gao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206250549292729.html