关闭

#30 Insert Interval

标签: lintcodeinterval
55人阅读 评论(0) 收藏 举报
分类:

题目描述:

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;
    }
};


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:12589次
    • 积分:2245
    • 等级:
    • 排名:第16835名
    • 原创:221篇
    • 转载:1篇
    • 译文:0篇
    • 评论:10条
    文章分类
    文章存档