8000 57, same with problem 56 · xzlin/LeetCode_Python_Accepted@68c8c7c · GitHub
[go: up one dir, main page]

Skip to content

Commit 68c8c7c

Browse files
committed
57, same with problem 56
1 parent 2a0db59 commit 68c8c7c

File tree

1 file changed

+15
-21
lines changed

1 file changed

+15
-21
lines changed

57_Insert_Interval.py

Lines changed: 15 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,22 @@
1-
# 2015-06-17 Runtime: 84 ms
1+
# 2016-03-21 151 tests, 108 ms
22

33
# Definition for an interval.
4-
# class Interval:
4+
# class Interval(object):
55
# def __init__(self, s=0, e=0):
66
# self.start = s
77
# self.end = e
88

9-
class Solution:
10-
# @param {Interval[]} intervals
11-
# @param {Interval} newInterval
12-
# @return {Interval[]}
9+
class Solution(object):
1310
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

Comments
 (0)
0