Leetcode 57. 插入区间

找到和插入区间相关的区间[l,r]代码中为[l,i-1)
进行可能的合并操作
最后放一个哨兵,从而一定能找到l,r

/**
* 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:
    const int inf = 0x3f3f3f3f;
    vector insert(vector& intervals, Interval newInterval) {
        vector ans;
        intervals.push_back(Interval(inf, inf));//哨兵,保证最后一个
        int i = 0;
        while (intervals[i].end < newInterval.start) ans.push_back(intervals[i++]);
        int l = i;
        while (intervals[i].start <= newInterval.end) ++i;
        if (l == i) ans.push_back(newInterval);
        else ans.push_back(Interval(min(intervals[l].start, newInterval.start), max(intervals[i - 1].end, newInterval.end)));
        while (i != intervals.size() - 1) ans.push_back(intervals[i++]);
        return ans;
    }
};

你可能感兴趣的:(Leetcode 57. 插入区间)