forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhi-rachel.py
More file actions
35 lines (29 loc) ยท 1.19 KB
/
hi-rachel.py
File metadata and controls
35 lines (29 loc) ยท 1.19 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
# https://leetcode.com/problems/insert-interval/
#
# ์๋ก์ด ๊ตฌ๊ฐ์ ๊ธฐ์กด์ ์ ๋ ฌ๋ ๊ตฌ๊ฐ ๋ฆฌ์คํธ์ ์ฝ์
ํ๊ณ , ๊ฒน์น๋ ๊ตฌ๊ฐ์ ๋ณํฉ
# ์ค๋ฆ์ฐจ์ ์ ๋ ฌ๋ [start, end] ํํ์ ๋ฆฌ์คํธ.
# ์๋ก์ด interval [newStart, newEnd]๋ฅผ ์ฝ์
ํ ํ์๋ ๊ตฌ๊ฐ์ด ๊ฒน์น์ง ์๊ณ ์ ๋ ฌ๋ ์ํ๋ก ์ ์ง.
#
# TC: O(N), ๊ฐ interval์ ์ต๋ ํ ๋ฒ์ฉ๋ง ํ์
# SC: O(N)
from typing import List
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
res = []
i = 0
n = len(intervals)
# 1. ์ผ์ชฝ์ ์๋ ๊ฒน์น์ง ์๋ ๊ตฌ๊ฐ
while i < n and intervals[i][1] < newInterval[0]:
res.append(intervals[i])
i += 1
# 2. ๊ฒน์น๋ ๊ตฌ๊ฐ ๋ณํฉ
while i < n and intervals[i][0] <= newInterval[1]:
newInterval[0] = min(newInterval[0], intervals[i][0])
newInterval[1] = max(newInterval[1], intervals[i][1])
i += 1
res.append(newInterval)
# 3. ์ค๋ฅธ์ชฝ์ ์๋ ๊ฒน์น์ง ์๋ ๊ตฌ๊ฐ
while i < n:
res.append(intervals[i])
i += 1
return res