8000 56, mix all starts and all ends then sort, check overlap · chaor/LeetCode_Python_Accepted@2a0db59 · GitHub
[go: up one dir, main page]

Skip to content

Commit 2a0db59

Browse files
committed
56, mix all starts and all ends then sort, check overlap
1 parent 82a5556 commit 2a0db59

File tree

1 file changed

+13
-14
lines changed

1 file changed

+13
-14
lines changed

56_Merge_Intervals.py

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,20 @@
1-
# 2015-06-17 Runtime: 102 ms
1+
# 2016-03-21 168 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-
# @return {Interval[]}
9+
class Solution(object):
1210
def merge(self, intervals):
13-
if len(intervals) == 0: return []
14-
intervals.sort(key = lambda x: x.start)
15-
result = [intervals[0]]
16-
for i in intervals:
17-
if i.start > result[-1].end:
18-
result.append(i)
19-
else:
20-
result[-1].end = max(result[-1].end, i.end)
21-
return result
11+
"""
12+
:type intervals: List[Interval]
13+
:rtype: List[Interval]
14+
"""
15+
result, overlap, begin = [], 0, float('-inf')
16+
for x, y in sorted([(i.start, 1) for i in intervals] + [(i.end, -1) for i in intervals], key = lambda x:(x[0], -x[1])):
17+
if y == 1 and not overlap: begin = x
18+
if y == -1 and overlap == 1: result += Interval(begin, x),
19+
overlap += y
20+
return result

0 commit comments

Comments
 (0)
0