首页 > 代码库 > 【LeetCode】Insert Interval

【LeetCode】Insert Interval

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].

 

由于insert和erase代价太大,需要移动后面所有元素。

所有空间换时间,返回新的数组ret,而不采用inplace做法。

主要以下三种情况:

1、newInterval在当前interval之前,则把newInterval装入ret,然后装入所有后续interval。返回ret。

2、newInterval与当前interval有交集,

(1)newInterval的end不大于当前interval的end,说明与后续元素没有交集,则合并为当前interval,然后将当前interval及后续interval装入ret。返回ret。

(2)newInterval的end大于当前interval的end

(2.1)newInterval的start大于当前interval的end,则将当前interval装入ret,然后处理下一个interval。

(2.2)newInterval的start不大于当前interval的end,则合并为新的newInterval,然后处理下一个interval。

3、处理完最后一个interval若仍未返回ret,说明newInterval为最后一个interval,装入ret。返回ret。

/** * 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> ret;        if(intervals.empty())        {//newInterval is ret            ret.push_back(newInterval);            return ret;        }        vector<Interval>::iterator it= intervals.begin();        while(it != intervals.end())        {            if(newInterval.end < (*it).start)            {//newInterval is strictly before (*it)                ret.push_back(newInterval);                while(it != intervals.end())                {                    ret.push_back(*it);                    it ++;                }                return ret; //end            }            else if(newInterval.end <= (*it).end)            {//remains unchanged or (*it).start=newIntervals.start                (*it).start = min((*it).start, newInterval.start);                while(it != intervals.end())                {                    ret.push_back(*it);                    it ++;                }                return ret; //end            }            else            {//newInterval.end > (*it).end                if(newInterval.start <= (*it).end)                {//overlap, change (*it) into newInterval                    if(newInterval.start > (*it).start)   //update start                        newInterval.start = (*it).start;                }                else                //newInterval is strictly after (*it)                    ret.push_back(*it);                it ++;            }        }        ret.push_back(newInterval);        return ret;    }};

【LeetCode】Insert Interval