30.插入区间

描述

Given a non-overlapping interval list which is sorted by start point.

Insert a new interval into it, make sure the list is still in order and non-overlapping (merge intervals if necessary).

您在真实的面试中是否遇到过这个题?  

样例

Insert (2, 5) into [(1,2), (5,9)], we get [(1,9)].

Insert (3, 4) into [(1,2), (5,9)], we get [(1,2), (3,4), (5,9)].

注意区间可能落在,已存在元素的范围内,例如:(3,7)插入[(1,2),(5,9)]


我开始的代码思路不太流畅,这个思路相对清晰,先修改要插入的元素的start end 最后统一删除容器中需要删除的元素。


/**
 * Definition of Interval:
 * class Interval {
 * public:
 *     int start, end;
 *     Interval(int start, int end) {
 *         this->start = start;
 *         this->end = end;
 *     }
 * }
 */


class Solution {
public:
    /*
     * @param intervals: Sorted interval list.
     * @param newInterval: new interval.
     * @return: A new interval list.
     */

    vector<Interval> insert(vector<Interval> intervals, Interval newInterval) {
        // write your code here
        int count = 0;
        int i = 0;
        while(i < intervals.size()){
            if(newInterval.end < intervals[i].start) break;
            else if(newInterval.start > intervals[i].end)
                ++i;
            else{
                newInterval.start = min(intervals[i].start,newInterval.start);
                newInterval.end = max(intervals[i].end,newInterval.end);
                ++i;
                ++count;
            }
        }
        if(count > 0) intervals.erase(intervals.begin()+i-count,intervals.begin()+i);
        intervals.insert(intervals.begin()+i-count,newInterval);
        return intervals;
    }

};

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页