每天两道LeetCodeHard:(10)

214 阅读1分钟

57. Insert Interval

经典的时间间隔问题

题干:

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.

解释:

经典的区间冲突问题,找到冲突的区间,然后合并。

思考:

思路区间冲突问题一般可以直接按照扫描时间线模板来解决,首先按照开始时间排序,然后放置点在时间线上,最后把时间线上大于0的区间全部合并重新输出即可。但是这个思路会挂掉,因为时间线扫描是不考虑[0,0]这种间隔的 更好的思路是逐个合并,先二分查找找到lower_bound,然后逐个合并到upper_bound,也就是俗称的暴力法,时间效率95%

注意找起点可以二分,找终点不能二分。

答案:

class Solution(object):
    def insert(self, intervals, newInterval):
        """
        :type intervals: List[List[int]]
        :type newInterval: List[int]
        :rtype: List[List[int]]
        """
        i =0
        n =len(intervals)
        #这一步是要找到插入位置,没有使用二分查找,可以优化
        while i<n and newInterval[0]>intervals[i][1]:
            i+=1
        left=i
        while i<n and newInterval[1]>=intervals[i][0]:
            i+=1
        right=i
        if left>=n:
            res=intervals+[newInterval]
        elif left==right:
            intervals.insert(left,newInterval)
            res=intervals
        else:
            res=intervals[:left]+[
                [min(intervals[left][0],newInterval[0]),max(intervals[right-1][1],newInterval[1])]
            ]+intervals[right:]
        return res

答案补充:

第一次遇到扫描时间线不能解决的问题,要加个教训了,因为扫描时间线实际上丢弃了原有的信息,所以还是在原数据基础上操作来的好