Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals[1,3],[6,9] , insert and merge [2,5] in as [1,5],[6,9] .
Given intervals
Example 2:
Given[1,2],[3,5],[6,7],[8,10],[12,16] , insert and merge [4,9] in as [1,2],[3,10],[12,16] .
Given
This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10] .
<Solution>這題和 merge intervals 算是姊妹題
不同的地方是,這題是要 insert 一個 newInterval 進來
並且把 overlap 的 interval 都拿掉,用最大的 interval 取代
解題想法如下(參考資料)
- 直接對原 vector 做操作,所以使用 iterator
- 當 newInterval.end 小於當前 interval.start,代表找到插入點了,離開迴圈
- 當 newInterval.start 大於當前 interval.end,沒有 overlap,什麼都不做
- 當不符合上述兩種情況,代表和當前 interval 有 overlap,這時候把 overlap 區間的最小值給 newInterval.start,最大值給 newInterval.end,overlap 的 counter 加1
- 從迴圈離開後,看看是否有 overlap,有的話就全部刪除
- 插入 newInterval
c++
Kotlin
沒有留言:
張貼留言