我是靠谱客的博主 醉熏豆芽,这篇文章主要介绍LeetCode-Python-57. 插入区间,现在分享给大家,希望可以做个参考。

给出一个无重叠的 ,按照区间起始端点排序的区间列表。

在列表中插入一个新的区间,你需要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。

示例 1:

复制代码
1
2
输入: intervals = [[1,3],[6,9]], newInterval = [2,5] 输出: [[1,5],[6,9]]

示例 2:

复制代码
1
2
3
输入: 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] 重叠。

思路:

跟LeetCode-Python-56. 合并区间类似,暴力解就是直接把新的区间插进去然后调用56的合并函数就好了。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# 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] """ # tmp = Interval(newInterval[0], newInterval[1]) intervals.append(newInterval) # intervals[-1] = newInterval # print type(intervals[0]), type(tmp) return self.merge(intervals) def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ if not intervals: return [] intervals = sorted(intervals,key=lambda x:x[0]) res = [] left = intervals[0][0] right = intervals[0][1] for item in intervals: if item[0] <= right: right = max(right, item[1]) else: res.append([left, right]) left = item[0] right = item[1] res.append([left, right]) return res

 

最后

以上就是醉熏豆芽最近收集整理的关于LeetCode-Python-57. 插入区间的全部内容,更多相关LeetCode-Python-57.内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(51)

评论列表共有 0 条评论

立即
投稿
返回
顶部