-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path56.MergeIntervals.py
45 lines (35 loc) · 1.32 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
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if len(intervals) == 1:
return intervals
# intervals.sort(key=lambda x: x[0])
intervals = self.my_sort(intervals)
i = 0
while i < len(intervals) - 1:
if intervals[i][1] >= intervals[i+1][1]:
intervals[i+1][1] = intervals[i][1]
intervals.pop(i+1)
i -= 1
elif intervals[i][1] >= intervals[i+1][0]:
intervals[i+1][0] = intervals[i][0]
intervals.pop(i)
i -= 1
i += 1
return intervals
def my_sort(self, x):
lx2 = len(x) // 2
return self.my_merge(self.merge(x[: lx2]), self.merge(x[lx2 :]))
def my_merge(self, left, right):
sorted_output = []
i, j, ll, lr = 0, 0, len(left), len(right)
while i < ll and j < lr:
if left[i][0] < right[j][0]:
sorted_output.append(left[i])
i += 1
else:
sorted_output.append(right[j])
j += 1
if i < ll:
return sorted_output + left[i:]
if j < lr:
return sorted_output + right[j:]