Skip to content

Commit 52b4d54

Browse files
committed
DaleStudy#278 merge-intervals solution
1 parent 4fa2889 commit 52b4d54

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

merge-intervals/sungjinwi.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"""
2+
풀이 :
3+
오름차순으로 interval을 정렬 후 ans의 마지막과 interval을 비교
4+
- 겹치는 구간이 있다면 합치고
5+
- 없다면 ans에 새로 interval을 추가한다
6+
7+
- 정렬을 쓰지 않고 풀었을 때:
8+
이중for문으로 비교하면서 merged라는 set로 중복검사되지 않도록 유의하면서 합친다
9+
겹치는 구간 또한 정렬되어 있지 않기 때문에 좀 더 복잡한 조건으로 비교해야함
10+
11+
interval 수 N
12+
13+
TC : O(N logN)
14+
정렬하는데 들어가는 시간 N logN + for문 N
15+
16+
SC : O(N)
17+
sorted(intervals)는 N에 비례, 결과 배열은 최악의 경우 N과 동일일
18+
"""
19+
20+
21+
class Solution:
22+
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
23+
ans = []
24+
for interval in sorted(intervals):
25+
if not ans:
26+
ans.append(interval)
27+
if interval[0] <= ans[-1][1]:
28+
ans[-1][1] = max(ans[-1][1], interval[1])
29+
else :
30+
ans.append(interval)
31+
return ans

0 commit comments

Comments
 (0)