美文网首页北美程序员面试干货
LeetCode 57 [Insert Interval]

LeetCode 57 [Insert Interval]

作者: Jason_Yuan | 来源:发表于2016-09-05 08:03 被阅读94次

原题

给出一个无重叠的按照区间起始端点排序的区间列表。
在列表中插入一个新的区间,你要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。

样例
插入区间[2, 5][[1,2], [5,9]],我们得到 [[1,9]]

插入区间
[3, 4]
[[1,2], [5,9]],我们得到** [[1,2], [3,4], [5,9]]**。

解题思路

  • 遍历每一个区间,进行更新,对区间和给定新区间进行判断,是否交叉
  • interval.end < newInterval.start,一定不交叉,该interval可以直接加入到result数组,但是insertPos要加一
  • interval.start > newInterval.end,也一定不交叉,直接把该interval加入到result数组
  • 剩下的情况,则表示两个interval交叉了,要更新newInterval的边界
newInterval.start = min(interval.start, newInterval.start)
newInterval.end = max(interval.end, newInterval.end)

完整代码

# Definition for an interval.
# class Interval(object):
#     def __init__(self, s=0, e=0):
#         self.start = s
#         self.end = e

class Solution(object):
    def insert(self, intervals, newInterval):
        """
        :type intervals: List[Interval]
        :type newInterval: Interval
        :rtype: List[Interval]
        """
        res = []
        insertPos = 0
        for interval in intervals:
            if interval.end < newInterval.start:
                res.append(interval)
                insertPos += 1
            elif interval.start > newInterval.end:
                res.append(interval)
            else:
                newInterval.start = min(interval.start, newInterval.start)
                newInterval.end = max(interval.end, newInterval.end)
        res.insert(insertPos, newInterval)
        return res

相关文章

网友评论

    本文标题:LeetCode 57 [Insert Interval]

    本文链接:https://www.haomeiwen.com/subject/wphrettx.html