forked from algorhythms/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
055 Merge Intervals.py
71 lines (61 loc) · 2.04 KB
/
055 Merge Intervals.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"""
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
"""
__author__ = 'Danyang'
# Definition for an interval.
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution(object):
def merge(self, itvls):
"""
scanning. No algorithm
math
:param itvls: a list of Interval
:return: a list of Interval
"""
if not itvls:
return []
itvls.sort(key=lambda x: x.start) # sort first, since time complexity less than brute force
ret = [itvls[0]]
for cur in itvls[1:]:
pre = ret[-1]
if cur.start <= pre.end: # overlap
pre.end = max(pre.end, cur.end)
else:
ret.append(cur)
return ret
def merge_error(self, itvls):
"""
scanning. No algorithm
math
:param itvls: a list of Interval
:return: a list of Interval
"""
if not itvls:
return []
ret = [itvls[0]]
for interval in itvls[1:]:
if ret[-1].end < interval.start:
ret.append(interval)
continue
if ret[-1].start <= interval.start <= ret[-1].end <= interval.end:
ret[-1].end = interval.end
continue
if interval.start <= ret[-1].start and ret[-1].end <= interval.end:
ret[-1] = interval
continue
if ret[-1].start <= interval.start < ret[-1].end and ret[-1].start <= interval.end < ret[-1].end:
ret.append(interval)
continue
if interval.start < ret[-1].start <= interval.end < ret[-1].end:
ret[-1].start = interval.start
continue
if interval.end < ret[-1].start:
ret.append(ret)
continue
return ret