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 by starti
. You are also given an interval newInterval = [start, end]
that represents the start and end of another interval.
Insert newInterval
into intervals
such that intervals
is still sorted in ascending order by starti
and intervals
still does not have any overlapping intervals (merge overlapping intervals if necessary).
Return intervals
after the insertion.
Note that you don't need to modify intervals
in-place. You can make a new array and return it.
Example 1:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]
Example 2:
Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
Constraints:
0 <= intervals.length <= 104
intervals[i].length == 2
0 <= starti <= endi <= 105
intervals
is sorted bystarti
in ascending order.newInterval.length == 2
0 <= start <= end <= 105
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
res = []
for interval in intervals :
if newInterval[1] < interval[0] :
res.append(newInterval)
newInterval = interval
elif newInterval[0] > interval[1] :
res.append(interval)
else :
newInterval[0] = min(newInterval[0], interval[0])
newInterval[1] = max(newInterval[1], interval[1])
res.append(newInterval)
return res
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
res = []
intervals.append(newInterval)
intervals.sort()
res.append(intervals[0])
for i in range(1, len(intervals)) :
if res[-1][1] >= intervals[i][0] :
res[-1][1] = max(res[-1][1], intervals[i][1])
else :
res.append(intervals[i])
return res
두 풀이의 메커니즘은 동일하다. 범위를 하나 정하고 범위에 해당하면 해당 범위와 비교해서 최소값과 최대값으로 범위를 늘리거나 새로운 범위로 갱신한다. 만약 범위에 속하지 않는다면 범위를 res에 넣고, 새로운 범위로 다시 저장한다. 이는 intervals[i][0]으로 정렬되어 있기 때문에 이렇게 한 것이다. 만약 문제에 저런 조건이 주어지지 않았다면, intervals.sort()를 먼저 한 후에 진행하는 것이 좋겠다.
'알고리즘 스터디' 카테고리의 다른 글
[Leetcode/파이썬] 125. Valid Palindrome (1) | 2025.09.22 |
---|---|
[Leetcode/파이썬] 242. Valid Anagram (0) | 2025.09.22 |
[Leetcode/파이썬] 1. Two Sum (1) | 2025.09.14 |
[Leetcode/파이썬] 64. Minimum Path Sum (0) | 2025.09.14 |
[Leetcode/파이썬] Insert Delete GetRandom O(1) (0) | 2025.09.14 |