#30 Insert Interval

题目描述:

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

Example

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

题目思路:

这题很容易做着做着就晕了,关键是要条理清楚。步骤如下:

1. 把new interval加入到intervals的array中,然后把整个array的所有区间根据start来sort

2. 遍历这个sort过的区间集合。如果发现本区间和上一个区间有overlap(本区间的start在上一个区间中),那么就合并本区间和上一个区间;然后不断的check下一个区间,如果有overlap就再进行合并,直到没有overlap为止。

3. 把最终的区间写到ans中。

这里loop到最后时,对于最后一个区间需要take care一下。

Mycode(AC = 26ms):

/**
 * Definition of Interval:
 * class Interval {
 * public:
 *     int start, end;
 *     Interval(int start, int end) {
 *         this->start = start;
 *         this->end = end;
 *     }
 * }
 */
class Solution {
public:
    /**
     * Insert newInterval into intervals.
     * @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
        vector<Interval> ans;
        
        // sort the whole intervals according to start
        auto comp = [](const Interval& a, const Interval& b) {
            return a.start <= b.start;    
        };
        
        intervals.push_back(newInterval);
        sort(intervals.begin(), intervals.end(), comp);
        
        int len = intervals.size();
        for (int i = 1; i < len; i++) {
            // if interval i has overlap with interval i - 1, then
            // merge 2 intervals
            while (i < len && intervals[i].start <= intervals[i - 1].end) {
                intervals[i].start = intervals[i - 1].start;
                intervals[i].end = max(intervals[i].end, intervals[i - 1].end);
                i++;
            }
            ans.push_back(intervals[i - 1]);
            if (i >= len) return ans;
        }
        
        ans.push_back(intervals[len - 1]);
        return ans;
    }
};


阅读更多
版权声明:三千微尘里,吾宁爱与憎 https://blog.csdn.net/haifischxia/article/details/52351962
文章标签: lintcode interval
个人分类: lintcode
想对作者说点什么? 我来说一句

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

不良信息举报

#30 Insert Interval

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭