文章目录
1 判重 / 合并 / 插入 区间
1.1 判断区间是否重叠
首先根据【start】进行排序;然后遍历,如果发现【当前-end】>【下个-start】,说明出现重叠
class Solution:
def canAttendMeetings(self, intervals: List[List[int]]) -> bool:
intervals.sort(key=lambda x: x[0])
n = len(intervals)
for i in range(n - 1):
if intervals[i][1] > intervals[i + 1][0]:
return False
return True
1.2 合并区间
对start进行排序之后,不妨设蓝色为元素0,橙色为元素1,总共3种情况,其中情况1、2是有重叠的。
设橙色为当前遍历元素itv
,蓝色为结果集最后一个元素res[-1]
,当不满足 res[-1].end < itv.start
时,需要更新res[-1].end
,否则将itv
append到结果集中
- 首先根据【start】进行排序;然后遍历:
- 如果结果集非空 且 不满足
res[-1].end < itv.start
时:- 更新
res[-1].end
- 更新
- 否则
- 将
itv
append到结果集中
- 将
- 如果结果集非空 且 不满足
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort(key=lambda x: x[0])
res = []
for itv in intervals:
if res and (not res[-1][1] < itv[0]):
res[-1][1] = max(res[-1]