[C++] LeetCode 57. 插入区间

题目

给出一个无重叠的 ,按照区间起始端点排序的区间列表。
在列表中插入一个新的区间,你需要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。
示例 1:

输入: intervals = [[1,3],[6,9]], newInterval = [2,5]
输出: [[1,5],[6,9]]

示例 2:

输入: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
输出: [[1,2],[3,10],[12,16]]

解释: 这是因为新的区间 [4,8][3,5],[6,7],[8,10]重叠。

代码

/**
 * 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;
        bool isuse=false;
        for(int i=0;i<intervals.size();i++){
            Interval t;
            if(isuse==false&&newInterval.start<=intervals[i].start){
                t=newInterval;
                isuse=true;
                i--;
            }
            else{
                t=intervals[i];
            }
            if(res.size()==0){
                res.push_back(t);
            }
            else{
                auto &tmp=res.back();
                if(t.start>=tmp.start&&t.start<=tmp.end)    tmp.end=max(tmp.end,t.end);
                else    res.push_back(t);
            }
        }
        if(isuse==false){            
            if(res.size()>0&&newInterval.start<=res.back().end){
                auto &tmp=res.back();
                tmp.end=max(newInterval.end,tmp.end);
            }   
            else
                res.push_back(newInterval);
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/lv1224/article/details/80959844