Skip to content

Commit 0cac923

Browse files
committed
insert-interval solution (py)
1 parent f7a9d09 commit 0cac923

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# https://leetcode.com/problems/insert-interval/
2+
#
3+
# ์ƒˆ๋กœ์šด ๊ตฌ๊ฐ„์„ ๊ธฐ์กด์˜ ์ •๋ ฌ๋œ ๊ตฌ๊ฐ„ ๋ฆฌ์ŠคํŠธ์— ์‚ฝ์ž…ํ•˜๊ณ , ๊ฒน์น˜๋Š” ๊ตฌ๊ฐ„์„ ๋ณ‘ํ•ฉ
4+
# ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ๋œ [start, end] ํ˜•ํƒœ์˜ ๋ฆฌ์ŠคํŠธ.
5+
# ์ƒˆ๋กœ์šด interval [newStart, newEnd]๋ฅผ ์‚ฝ์ž…ํ•œ ํ›„์—๋„ ๊ตฌ๊ฐ„์ด ๊ฒน์น˜์ง€ ์•Š๊ณ  ์ •๋ ฌ๋œ ์ƒํƒœ๋กœ ์œ ์ง€.
6+
#
7+
# TC: O(N), ๊ฐ interval์„ ์ตœ๋Œ€ ํ•œ ๋ฒˆ์”ฉ๋งŒ ํƒ์ƒ‰
8+
# SC: O(N)
9+
10+
from typing import List
11+
12+
class Solution:
13+
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
14+
res = []
15+
i = 0
16+
n = len(intervals)
17+
18+
# 1. ์™ผ์ชฝ์— ์žˆ๋Š” ๊ฒน์น˜์ง€ ์•Š๋Š” ๊ตฌ๊ฐ„
19+
while i < n and intervals[i][1] < newInterval[0]:
20+
res.append(intervals[i])
21+
i += 1
22+
23+
# 2. ๊ฒน์น˜๋Š” ๊ตฌ๊ฐ„ ๋ณ‘ํ•ฉ
24+
while i < n and intervals[i][0] <= newInterval[1]:
25+
newInterval[0] = min(newInterval[0], intervals[i][0])
26+
newInterval[1] = max(newInterval[1], intervals[i][1])
27+
i += 1
28+
res.append(newInterval)
29+
30+
# 3. ์˜ค๋ฅธ์ชฝ์— ์žˆ๋Š” ๊ฒน์น˜์ง€ ์•Š๋Š” ๊ตฌ๊ฐ„
31+
while i < n:
32+
res.append(intervals[i])
33+
i += 1
34+
35+
return res

0 commit comments

Comments
ย (0)