Skip to content

Commit e4e23ac

Browse files
committed
feat: solve DaleStudy#278 with python
1 parent 68baacf commit e4e23ac

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

merge-intervals/EGON.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
from typing import List
2+
from unittest import TestCase, main
3+
4+
5+
class Solution:
6+
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
7+
return self.solve_stack(intervals)
8+
9+
"""
10+
Runtime: 8 ms (Beats 49.77%)
11+
Time Complexity:
12+
- intervals의 길이를 n이라 하면, intervals를 시작 지점을 기준으로 정렬하는데 O(n log n)
13+
- intervals를 조회하면서 연산하는데, 내부 연산은 모두 O(1)이므로 O(n)
14+
> O(n log n) + O(n) ~= O(n log n)
15+
16+
Memory: 19.88 MB (Beats: 99.31%)
17+
Space Complexity: O(n)
18+
- intervals는 내부 정렬만 했으므로 추가 메모리 사용 메모리 없음
19+
- 겹치는 구간이 없는 최악의 경우 merged의 크기는 intervals의 크기와 같아지므로, O(n) upper bound
20+
"""
21+
22+
def solve_stack(self, intervals: List[List[int]]) -> List[List[int]]:
23+
intervals.sort()
24+
25+
merged = []
26+
for interval in intervals:
27+
if not merged:
28+
merged.append(interval)
29+
continue
30+
31+
new_start, new_end = interval
32+
_, last_end = merged[-1]
33+
if last_end < new_start:
34+
merged.append(interval)
35+
else:
36+
merged[-1][1] = max(last_end, new_end)
37+
38+
return merged
39+
40+
41+
class _LeetCodeTestCases(TestCase):
42+
43+
def test_1(self):
44+
intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]
45+
output = [[1, 6], [8, 10], [15, 18]]
46+
47+
self.assertEqual(Solution().merge(intervals), output)
48+
49+
def test_2(self):
50+
intervals = [[1, 4], [4, 5]]
51+
output = [[1, 5]]
52+
53+
self.assertEqual(Solution().merge(intervals), output)
54+
55+
56+
if __name__ == '__main__':
57+
main()

0 commit comments

Comments
 (0)