Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] Output: [[1,2],[3,10],[12,16]] Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution(object): definsert(self, intervals, newInterval): """ :type intervals: List[List[int]] :type newInterval: List[int] :rtype: List[List[int]] """ nl, nh = newInterval[0], newInterval[1] itvs = [[i[0], i[1]] for i in intervals] left, right = [], [] for l, h in itvs: if h < nl: left += [l, h], elif l > nh: right += [l, h], else: nl, nh = min(nl, l), max(nh, h) return left + [[nl, nh]] + right
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution(object): definsert(self, intervals, newInterval): """ :type intervals: List[List[int]] :type newInterval: List[int] :rtype: List[List[int]] """ intervals.append(newInterval) out = [] for i in sorted(intervals, key=lambda i: i[0]): if out and i[0] <= out[-1][1]: out[-1][1] = max(out[-1][1], i[1]) else: out += i, return out