|
| 1 | +# 57. Insert Interval (Python) |
| 2 | +## Problem |
| 3 | +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. |
| 4 | + |
| 5 | +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). |
| 6 | + |
| 7 | +Return intervals after the insertion. |
| 8 | + |
| 9 | +**Example 1:** |
| 10 | +``` |
| 11 | +Input: intervals = [[1,3],[6,9]], newInterval = [2,5] |
| 12 | +Output: [[1,5],[6,9]] |
| 13 | +``` |
| 14 | + |
| 15 | +**Example 2:** |
| 16 | +``` |
| 17 | +Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] |
| 18 | +Output: [[1,2],[3,10],[12,16]] |
| 19 | +Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]. |
| 20 | +``` |
| 21 | + |
| 22 | +## Constraints: |
| 23 | +- 0 <= intervals.length <= 104 |
| 24 | +- intervals[i].length == 2 |
| 25 | +- 0 <= starti <= endi <= 105 |
| 26 | +- intervals is sorted by starti in ascending order. |
| 27 | +- newInterval.length == 2 |
| 28 | +- 0 <= start <= end <= 105 |
| 29 | + |
| 30 | +## Solution 1. |
| 31 | +這一解法分成三步驟: |
| 32 | + |
| 33 | +1. 將小於 newInterval 的區間塞入 newList 直到 newInterval[0]>intervals[i][1] |
| 34 | +2. 將有覆蓋到 newInterval 的區間合併,同時找出 min start 和 max end |
| 35 | +3. 塞入剩下未涵蓋的區間 |
| 36 | + |
| 37 | +- 串列處理、Graph |
| 38 | +- Run Time: 63 ms |
| 39 | + |
| 40 | +```py |
| 41 | +class Solution(object): |
| 42 | + def insert(self, intervals, newInterval): |
| 43 | + |
| 44 | + newList=[] |
| 45 | + i=0 |
| 46 | + # add all the intervals ending before newInterval starts |
| 47 | + while i<len(intervals) and newInterval[0]>intervals[i][1]: |
| 48 | + newList.append(intervals[i]) |
| 49 | + i+=1 |
| 50 | + # merge all overlapping intervals to one considering newInterval |
| 51 | + while i<len(intervals) and newInterval[1]>=intervals[i][0]: |
| 52 | + newInterval = [min(newInterval[0],intervals[i][0]), max(newInterval[1],intervals[i][1])] |
| 53 | + i+=1 |
| 54 | + newList.append(newInterval) # add the union of intervals we got |
| 55 | + # add all the rest |
| 56 | + while i<len(intervals): |
| 57 | + newList.append(intervals[i]) |
| 58 | + i+=1 |
| 59 | + |
| 60 | + return newList |
| 61 | +``` |
0 commit comments