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

57. Insert Interval

时间:2017-08-18 20:05:05      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:necessary   操作   时间   sorted   .net   pre   before   str   代码   

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

使用的for 循环恶心死, while 先找插入位置, 再不断合并中间重复的interval, 最后直接再加上后面的, while 中的条件可以画图得到

这道题跟Merge Intervals很类似,都是关于数据结构interval的操作。事实上,Merge Intervals是这道题的子操作,就是插入一个interval,如果出现冲突了,就进行merge。跟Merge Intervals不一样的是,这道题不需要排序,因为插入之前已经默认这些intervals排好序了。简单一些的是这里最多只有一个连续串出现冲突,因为就插入那么一个。基本思路就是先扫描走到新的interval应该插入的位置,接下来就是插入新的interval并检查后面是否冲突,一直到新的interval的end小于下一个interval的start,然后取新interval和当前interval中end大的即可。因为要进行一次线性扫描,所以时间复杂度是O(n)。而空间上如果我们重新创建一个ArrayList返回,那么就是O(n)。有朋友可能会说为什么不in-place的进行操作,这样就不需要额外空间,但是如果使用ArrayList这个数据结构,那么删除操作是线性的,如此时间就不是O(n)的。如果这道题是用LinkedList那么是可以做到in-place的,并且时间是线性的。代码如下:

public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
    List<Interval> result = new LinkedList<>();
    int i = 0;
    // add all the intervals ending before newInterval starts
    while (i < intervals.size() && intervals.get(i).end < newInterval.start)
        result.add(intervals.get(i++));
    // merge all overlapping intervals to one considering newInterval
    while (i < intervals.size() && intervals.get(i).start <= newInterval.end) {
        newInterval = new Interval( // we could mutate newInterval here also
                Math.min(newInterval.start, intervals.get(i).start),
                Math.max(newInterval.end, intervals.get(i).end));
        i++;
    }
    result.add(newInterval); // add the union of intervals we got
    // add all the rest
    while (i < intervals.size()) result.add(intervals.get(i++)); 
    return result;
}

这道题有一个变体,就是如果插入的时候发现冲突,那就返回失败,不插入了。看起来好像比上面这道题还要简单,但是要注意的是,如此我们就不需要进行线性扫描了,而是进行二分查找,如果不冲突,则进行插入,否则直接返回失败。这样时间复杂度可以降低到O(logn)。当然这里需要用二分查找树去维护这些intervals。所以一点点变化可能可以使复杂度降低,还是应该多做思考哈。
同时,这种题目还可以问一些关于OO设计的东西,比如就直接问你要实现一个intervals的类,要维护哪些变量,实现哪些功能,用什么数据结构,等等。这些你可以跟面试官讨论,然后根据他的功能要求用相应的数据结构。所以扩展性还是很强的,大家可以考虑的深入一些。

 

57. Insert Interval

标签:necessary   操作   时间   sorted   .net   pre   before   str   代码   

原文地址:http://www.cnblogs.com/apanda009/p/7391265.html

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