|
| 1 | +/* 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. |
| 2 | +
|
| 3 | +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). |
| 4 | +
|
| 5 | +Return intervals after the insertion. |
| 6 | +
|
| 7 | +Example 1: |
| 8 | +
|
| 9 | +Input: intervals = [[1,3],[6,9]], newInterval = [2,5] |
| 10 | +Output: [[1,5],[6,9]] |
| 11 | +*/ |
| 12 | + |
| 13 | + |
| 14 | +class Solution { |
| 15 | +public: |
| 16 | + vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) { |
| 17 | + // get the number of intervals and initialize an index variable |
| 18 | + int n = intervals.size(), i = 0; |
| 19 | + // initialize a vector to store the result |
| 20 | + vector<vector<int>> res; |
| 21 | + |
| 22 | + // loop through the intervals until the end or until the end of the first interval that comes after the new interval |
| 23 | + while(i < n && intervals[i][1] < newInterval[0]){ |
| 24 | + // add the current interval to the result |
| 25 | + res.push_back(intervals[i]); |
| 26 | + i++; |
| 27 | + } |
| 28 | + // loop through the intervals that overlap with the new interval |
| 29 | + while(i < n && newInterval[1] >= intervals[i][0]){ |
| 30 | + // update the start and end of the new interval to include the current interval |
| 31 | + newInterval[0] = min(newInterval[0], intervals[i][0]); |
| 32 | + newInterval[1] = max(newInterval[1], intervals[i][1]); |
| 33 | + i++; |
| 34 | + } |
| 35 | + // add the new interval to the result |
| 36 | + res.push_back(newInterval); |
| 37 | + |
| 38 | + // add the remaining intervals to the result |
| 39 | + while(i < n){ |
| 40 | + res.push_back(intervals[i]); |
| 41 | + i++; |
| 42 | + } |
| 43 | + // return the result |
| 44 | + return res; |
| 45 | + } |
| 46 | +}; |
| 47 | + |
0 commit comments