-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02_MergeIntervals.py
More file actions
42 lines (30 loc) · 1.13 KB
/
02_MergeIntervals.py
File metadata and controls
42 lines (30 loc) · 1.13 KB
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
# Question link - https://leetcode.com/problems/merge-intervals/?envType=study-plan-v2&envId=top-interview-150
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
n = len(intervals)
intervals.sort()
ans = []
for i in range(n):
if not ans or intervals[i][0] > ans[-1][1]:
ans.append(intervals[i])
# if the current interval
# lies in the last interval:
else:
ans[-1][1] = max(ans[-1][1], intervals[i][1])
return ans
# # Approach 1 - Brute force
# # Brute approch
# for i in range(n):
# start = intervals[i][0]
# end = internvals[i][1]
# # skip all the elements
# if ans and end <= intervals[-1][1]:
# continue
# #check the rest of the intervals
# for j in range(i+1,n):
# if intervals[j][0] <= end:
# end = max(end , intervals[j][1])
# else:
# break
# ans.append([start , end])
# return ans