题解 | #合并区间#
合并区间
https://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a
from functools import cmp_to_key # class Interval: # def __init__(self, a=0, b=0): # self.start = a # self.end = b # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param intervals Interval类一维数组 # @return Interval类一维数组 # class Solution: def merge(self , intervals: List[Interval]) -> List[Interval]: # write code here # 方法一:方法会超时,但没理解为啥会超时 # if not intervals: # return [] # intervals.sort(key=lambda x:x.start) # l, r = 0, 1 # while r<len(intervals): # if intervals[l].end<intervals[r].start: # l += 1 # r += 1 # else: # intervals[l].end = max(intervals[l].end,intervals[r].end) # intervals.pop(r) # return intervals # 方法二 if not intervals: return [] intervals.sort(key=lambda x:x.start) res = [] res.append(intervals[0]) for i in range(1,len(intervals)): if intervals[i].start <= res[-1].end: res[-1].end = max(intervals[i].end, res[-1].end) else: res.append(intervals[i]) return res