-
Notifications
You must be signed in to change notification settings - Fork 0
/
56_MergeIntervals.py
86 lines (77 loc) · 2.76 KB
/
56_MergeIntervals.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# Definition for an interval.
class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
def __repr__(self):
return str([self.start, self.end])
class Solution:
def parse(self, intervals):
result = []
for interval in intervals:
result.append(Interval(interval[0], interval[1]))
return self.merge(result)
# @param {Interval[]} intervals
# @return {Interval[]}
def merge(self, intervals):
result = []
for inter in sorted(intervals, key=lambda x: x.start):
if result and inter.start <= result[-1].end:
result[-1].end = max(inter.end, result[-1].end)
else:
result.append(inter)
return result
def bmerge(self, intervals):
intervals = sorted(intervals[:], key=lambda inter: inter.start)
idx = 0
while True:
if idx > (len(intervals) - 2):
break
intera, interb = intervals[idx], intervals[idx+1]
if intera.start > interb.end or intera.end < interb.start:
idx += 1
else:
start = intera.start
if intera.start > interb.start:
start = interb.start
end = intera.end
if intera.end < interb.end:
end = interb.end
del intervals[idx:idx+2]
intervals.insert(idx, Interval(start, end))
return intervals
def amerge(self, intervals):
result = sorted(intervals[:], key=lambda inter: inter.start)
while True:
tmp = result[:]
intera, interb = self.hasOverlap(tmp)
if intera == None and interb == None:
break
else:
idx = min(tmp.index(intera), tmp.index(interb))
tmp.remove(intera)
tmp.remove(interb)
start = intera.start
if intera.start > interb.start:
start = interb.start
end = intera.end
if intera.end < interb.end:
end = interb.end
tmp.insert(idx, Interval(start, end))
result = tmp
return result
def hasOverlap(self, intervals):
tmp = intervals[:]
while tmp:
target = tmp.pop()
for interval in tmp:
# no crossing
if interval.start > target.end or interval.end < target.start:
continue
else:
return target, interval
return None, None
if __name__ == "__main__":
sol = Solution()
print sol.parse([[1,3],[2,6],[8,10],[15,18]])
print sol.parse([[1,4],[1,4]])