LeetCode | 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:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].

Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].

This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].

题目解析:

题目很简单,如果新插入的范围能够使原始范围合并,就合并之。但要注意分情况:整体在i结点前,整体在i结点后,new.start<i.start 以及new.start>=i.start。考虑全情况以后,代码就好写了。

由于设置了一个新的容器,而不是基于原容器修改的,所以到最后要判断newInterval是否已经插入到res中。

class Solution {
public:
    vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
        vector<Interval> res;

        int len = intervals.size();
        bool flag = false;  //判断newInterval是否已经被插入到res中,如果没有的话,在循环结束后插入新的区域

        for(int i = 0;i < len;i++){
            //如果newInterval在i前面就直接插入,然后将后续的结点插入返回
            if(newInterval.end < intervals[i].start){
                flag = true;
                res.push_back(newInterval);
                while(i < len)
                    res.push_back(intervals[i++]);
                break;
            }
            //如果new整体在后面,插入当前结点i,继续向后找
            if(newInterval.start > intervals[i].end){
                res.push_back(intervals[i]);
                continue;
            }
            //当new.start在i.start前面时
            if(newInterval.start < intervals[i].start && newInterval.end >= intervals[i].start){
                newInterval.end = max(newInterval.end,intervals[i].end);
                continue;
            }
            //当new.start在i.start...i.end之间时
            if(newInterval.start >= intervals[i].start && newInterval.start <= intervals[i].end){
                newInterval.start = intervals[i].start;
                newInterval.end = max(newInterval.end,intervals[i].end);
            }
        }
        if(!flag)
            res.push_back(newInterval);
        return res;
    }
};

点赞