Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- Array
- tree
- backtracking
- Depth-first Search
- Medium
- linked list
- Binary
- recursive
- binary tree
- Python
- string
- leetcode
- dfs
- 이진트리
- math
- 미디움
- 재귀
- easy
- 리트코드
- list
- 문자열
- HashTable
- DP
- sorting
- binary search
- two pointers
- 중간
- hash table
- 쉬움
- matrix
Archives
- Today
- Total
부부의 코딩 성장 일기
LeetCode 57(Insert Interval, Python) 본문
1. 문제 링크
Insert Interval - LeetCode
Can you solve this real interview question? Insert Interval - You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order b
leetcode.com
2. 문제 설명
- 주어진 배열 intervals는 시작과 끝을 나타내는 요소들을 가지고 있고, 새로운 interval을 나타내는 newInterval이 주어졌을 때,
- 이를 intervals에 삽입하여, 삽입 후의 intervals를 반환
- 단, intervals는 시작 값이 오름차순으로 정렬되어 있어야 하며, 겹치는 구간이 없도록 삽입을 해야 함.
- 겹치는 구간이 있다면 그것들을 합쳐야 함. (직전 문제와 유사한 문제)
- 예시1) intervals=[[1,3],[6,9]], newInterval=[2,5]일 때, output=[[1,5],[6,9]]
- 예시2) intervals=[[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval=[4,8] 이면 output=[[1,2],[3,10],[12,16]]
- 왜냐하면 newInterval인 [4,8]은 [3,5], [6,7], [8,10]과 overlap 되기 때문
3. 처음 풀이
- leetcode 직전 문제인 "Merge Intervals"에 하나의 변화만 주어 코드 작성
- newInterval을 intervals에 append 시킨 후, 이를 sort()시킨 이후에, Merge Intervals와 유사하게 풀이
- merged 라는 array를 만들어두고,
- interval element의 첫번째 값이 merged array의 마지막 element의 두번째 값보다 작거나 같으면, merged[-1][1] 값을 업데이트하고, 그 외의 경우는 [start,end]를 append 하여
- 최종적으로 merged array 반환
- merged 라는 array를 만들어두고,
- newInterval을 intervals에 append 시킨 후, 이를 sort()시킨 이후에, Merge Intervals와 유사하게 풀이
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
intervals.append(newInterval)
intervals.sort()
merged = [intervals[0]]
for start, end in intervals[1:]:
if start<=merged[-1][1]:
merged[-1][1] = max(merged[-1][1], end)
else:
merged.append([start, end])
return merged
4. 다른 풀이
- submission에서 runtime이 높았던 풀이
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
res=[]
for i in range(len(intervals)):
if newInterval[1]<intervals[i][0]:
res.append(newInterval)
return res+intervals[i:]
elif newInterval[0]>intervals[i][1]:
res.append(intervals[i])
else:
newInterval = [min(newInterval[0],intervals[i][0]),max(newInterval[1],intervals[i][1])]
res.append(newInterval)
return res
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode 61(Rotate List, Python) (1) | 2024.01.14 |
---|---|
LeetCode 59(Spiral Matrix II, Python) (1) | 2024.01.13 |
LeetCode 56(Merge Intervals, Python) (1) | 2024.01.11 |
LeetCode 55(Jump Game, Python) (0) | 2024.01.10 |
LeetCode 54(Spiral Matrix, Python) (0) | 2024.01.09 |