File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
1
+ # https://leetcode.com/problems/merge-intervals/
2
+
3
+ from typing import List
4
+
5
+ class Solution :
6
+ def merge (self , intervals : List [List [int ]]) -> List [List [int ]]:
7
+ """
8
+ [Complexity]
9
+ - TC: O(nlogn) (sorting)
10
+ - SC: O(1) (res 제외)
11
+
12
+ [Approach]
13
+ intervals를 오름차순 정렬하면, 이를 순회하면서 끝 값만 비교하며 interval이 서로 겹치는 경우와 겹치지 않는 경우를 판단할 수 있다.
14
+ 이전 interval과 겹치는 경우라면, 이전 끝 값과 현재 끝 값 중 큰 값으로 업데이트하면 된다.
15
+ """
16
+ res = []
17
+
18
+ # interval의 시작 값이 작은 순으로 정렬
19
+ # -> intervals를 순회하며 끝 값만 비교하며 non-overlapping/overlapping interval 판단 가능
20
+ intervals .sort ()
21
+
22
+ for s , e in intervals :
23
+ # (1) non-overlapping: res가 비었거나, 이전 e < 현재 s인 경우 -> 그대로 추가
24
+ if not res or res [- 1 ][1 ] < s :
25
+ res .append ([s , e ])
26
+ # (2) overlapping: 이전 e >= 현재 s인 경우 -> 이전 e와 현재 e 중 큰 값으로 업데이트
27
+ else :
28
+ res [- 1 ][1 ] = max (res [- 1 ][1 ], e )
29
+
30
+ return res
You can’t perform that action at this time.
0 commit comments