LeetCode 题解:57. Insert Interval

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

You may assume that the intervals were initially sorted according to their start times.

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]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].

解题思路

本题解答过程分三步:

**第一步:**将所有区间右边界小于插入区间左边界的原区间保存至结果数组

**第二步:**合并所有与插入区间有重叠部分的区间(包括边界重叠),分为四种情况

a. 插入区间的左边界小于原区间的左边界(共两种)

(1)原区间的右边界大于插入区间的右边界,两区间合并成左边界为插入区间的左边界、右边界为原区间右边界的新区间

(2)原区间的右边界小于等于插入区间的右边界,原区间合并到插入区间中

b. 插入区间的左边界大于等于原区间的左边界(共两种)

(1)原区间的右边界大于插入区间的右边界,插入区间合并到原区间中

(2)原区间的右边界小于等于插入区间的右边界,两区间合并成左边界为原区间的左边界、右边界为插入区间的右边界的新区间

**第三步:**将所有区间左边界大于插入区间右边界的原区间保存至结果数组,完成

C++代码

/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
class Solution {
public:
    vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
        vector<Interval> res;
        Interval temp = newInterval;
        int rec = 0;
        // 将插入区间前面的不重叠区间保存至结果数组
        for(int i = 0; i < intervals.size(); i++) {
            if(intervals[i].end < newInterval.start){
                res.push_back(intervals[i]);
                rec++;
            }
        }
        
        for(int i = rec; i < intervals.size(); i++) {
            if(intervals[i].start > temp.end){
                break;
            }
            else {
                if(intervals[i].start > temp.start) {
                    if(intervals[i].end > temp.end) {
                        Interval t(temp.start, intervals[i].end);
                        temp = t;
                    }
                    else {
                        temp = temp;
                    }
                }
                else{
                    if(intervals[i].end > temp.end) {
                        temp = intervals[i];
                    }
                    else {
                        Interval t(intervals[i].start, temp.end);
                        temp = t;
                    }
                }
                rec++;
            }
        }
        // 将合并后区间保存至结果数组
        res.push_back(temp);
        
        // 将插入区间后面的不重叠区间保存至结果数组
        for(int i = rec; i < intervals.size(); i++) {
            if(intervals[i].start > temp.end){
                res.push_back(intervals[i]);
            }
        }
        return res;
    }
};

你可能感兴趣的:(LeetCode题解,C++,LeetCode)