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

 

解题思路:

新的interval(newInterval)与现在的interval(cur)之间的关系有以下几种:

  1. cur.end < newInterval.start: 此时两个interval不重合,我们可以先将cur插入到返回数组中

  需要注意的是:现在不能够插入newInterval 因为后面的interval也有可能比它小

  2.cur.start > newInterval.end: 此时说明newInterval整体小于cur,我们要先将newInterval插入,然后再把cur插入

  3.cur和newInterval相交叉:首先merge两个interval并将新的interval作为newInterval继续尝试插入

需要注意的是:

  1.为了防止反复插入newInterval,我用了一个bool变量(ist)来标记newInterval是否已经被插入过

  2.很有可能所有的interval都比newInterval要小,所以我们要记得最后根据ist来判断newInterval是否被插入,如果没有,就要插入。

代码:

/**
 * 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;
        bool ist = false;
        for(int i = 0; i < intervals.size(); i++){
            Interval cur = intervals[i];
            if(cur.end < newInterval.start){
                ret.push_back(cur);
                continue;
            }
            if(cur.start > newInterval.end){
                if(!ist){
                    ret.push_back(newInterval);
                    ist = true;
                }
                ret.push_back(cur);
                continue;
            }
            //need to merge
            newInterval.start = min(cur.start, newInterval.start);
            newInterval.end = max(cur.end, newInterval.end); 
        }
        if(!ist){
            ret.push_back(newInterval);
        }
        return ret;
    }
};

 

posted @ 2018-06-13 05:10  妖域大都督  阅读(88)  评论(0编辑  收藏  举报