Leetcode 57.插入区间(Insert Interval)

Leetcode 57.插入区间

1 题目描述(Leetcode题目链接

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

输入: intervals = [[1,3],[6,9]], newInterval = [2,5]
输出: [[1,5],[6,9]]
输入: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
输出: [[1,2],[3,10],[12,16]]
解释: 这是因为新的区间 [4,8][3,5],[6,7],[8,10] 重叠。

2 题解

  和合并区间是一样的。

class Solution:
    def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
        intervals.append(newInterval)
        intervals = sorted(intervals, key = lambda x:x[0])
        retv = []
        for i in intervals:
            if not retv or i[0] > retv[-1][1]:
                retv.append(i)
            else: 
                retv[-1][1] = max(i[1], retv[-1][1])
        return retv
发布了264 篇原创文章 · 获赞 63 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_39378221/article/details/104938242