码迷,mamicode.com
首页 > 其他好文 > 详细

Insert Interval -- leetcode

时间:2015-03-28 14:27:39      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:leetcode   区间   合并   面试   merge   

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]


/**
 * 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) {
        auto iter = intervals.begin();
        while (iter != intervals.end() &&
            iter->end < newInterval.start)
            ++iter;
        
        if (iter != intervals.end()) {
            auto iend = iter;
            while (iend != intervals.end() &&
                 newInterval.end >= iend->start)
                ++iend;
                
            if (iter != iend) {
                newInterval.start = min(newInterval.start, iter->start);
                --iend;
                newInterval.end = max(newInterval.end, iend->end);
                ++iend;
            
                iter = intervals.erase(iter, iend);
            }
        }
        
        intervals.insert(iter, newInterval);
        return intervals;
    }
};

该算法在leetcode上实际执行时间为16ms。

基本思路为,

在数组中找到和待插入的区间有重叠的所以区间 [iter, iend), 注,左闭右开。

若存在,合并区间信息到待插入区间。并删除原有的重叠区间。

若不存在,则直接插入。


所要注意的事项为,用范围删除,即先找到范围,再整体删除。

如果找到一个区间,就删除一个。 在运行时间上将不能被AC。


Insert Interval -- leetcode

标签:leetcode   区间   合并   面试   merge   

原文地址:http://blog.csdn.net/elton_xiao/article/details/44699953

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!