1
- # 2015-06-17 Runtime: 84 ms
1
+ # 2016-03-21 151 tests, 108 ms
2
2
3
3
# Definition for an interval.
4
- # class Interval:
4
+ # class Interval(object) :
5
5
# def __init__(self, s=0, e=0):
6
6
# self.start = s
7
7
# self.end = e
8
8
9
- class Solution :
10
- # @param {Interval[]} intervals
11
- # @param {Interval} newInterval
12
- # @return {Interval[]}
9
+ class Solution (object ):
13
10
def insert (self , intervals , newInterval ):
14
- result , i = [], 0
15
- # add all intervals ending before newInterval starts
16
- while i < len (intervals ) and intervals [i ].end < newInterval .start :
17
- result .append (intervals [i ])
18
- i += 1
19
- # merge all overlapping intervals to one considering newInterval
20
- while i < len (intervals ) and intervals [i ].start <= newInterval .end :
21
- newInterval .start , newInterval .end = min (newInterval .start , intervals [i ].start ), max (newInterval .end , intervals [i ].end )
22
- i += 1
23
- result .append (newInterval ) # add the union of intervals we got
24
- # add all the rest
25
- while i < len (intervals ):
26
- result .append (intervals [i ])
27
- i += 1
28
- return result
11
+ """
12
+ :type intervals: List[Interval]
13
+ :type newInterval: Interval
14
+ :rtype: List[Interval]
15
+ """
16
+ result , overlap , begin = [], 0 , float ('-inf' )
17
+ for x , y in sorted ([(i .start , 1 ) for i in intervals ] + [(i .end , - 1 ) for i in intervals ] +
18
+ [(newInterval .start , 1 ), (newInterval .end , - 1 )], key = lambda x :(x [0 ], - x [1 ])):
19
+ if y == 1 and not overlap : begin = x
20
+ if y == - 1 and overlap == 1 : result += Interval (begin , x ),
21
+ overlap += y
22
+ return result
0 commit comments