57. Insert Interval

2019-05-09

57. Insert Interval

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

You may assume that the intervals were initially sorted according to their start times.

Example 1:

1
2
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]

Example 2:

1
2
3
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
class Solution(object):
def insert(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
class Solution(object):
def insert(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
-->