|
| 1 | +/* |
| 2 | + Given a set of non-overlapping intervals, insert a new interval into the |
| 3 | + intervals (merge if necessary). |
| 4 | + You may assume that the intervals were initially sorted according to their |
| 5 | + start times. |
| 6 | +
|
| 7 | + Example 1: |
| 8 | + Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]. |
| 9 | +
|
| 10 | + Example 2: |
| 11 | + Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as |
| 12 | + [1,2],[3,10],[12,16]. |
| 13 | +
|
| 14 | + This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10]. |
| 15 | +*/ |
| 16 | + |
| 17 | +/** |
| 18 | + * Definition for an interval. |
| 19 | + * struct Interval { |
| 20 | + * int start; |
| 21 | + * int end; |
| 22 | + * Interval() : start(0), end(0) {} |
| 23 | + * Interval(int s, int e) : start(s), end(e) {} |
| 24 | + * }; |
| 25 | + */ |
| 26 | +class Solution { |
| 27 | +public: |
| 28 | + /* |
| 29 | + *Find the position which the newInterval inserts after. |
| 30 | + */ |
| 31 | + int findInsertPos(vector<Interval> &intervals, Interval &newInterval) { |
| 32 | + int l = 0, r = intervals.size() - 1, mid; |
| 33 | + while (l <= r) { |
| 34 | + mid = (l + r) / 2; |
| 35 | + if (newInterval.start >= intervals[mid].start) { |
| 36 | + l = mid + 1; |
| 37 | + } else { |
| 38 | + r = mid - 1; |
| 39 | + } |
| 40 | + } |
| 41 | + return l; |
| 42 | + } |
| 43 | + |
| 44 | + vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) { |
| 45 | + vector<Interval> result; |
| 46 | + if (intervals.size() == 0) { |
| 47 | + result.push_back(newInterval); |
| 48 | + return result; |
| 49 | + } |
| 50 | + int pos = findStartPos(intervals, newInterval); |
| 51 | + int n = intervals.size(), i = 0; |
| 52 | + |
| 53 | + // Before newInterval inserts, the original intervals are the same as |
| 54 | + // before. |
| 55 | + for (; i<pos; i++) { |
| 56 | + result.push_back(intervals[i]); |
| 57 | + } |
| 58 | + |
| 59 | + // The newInterval does not overlap with preceding interval. |
| 60 | + if (result.empty() || result.back().end < newInterval.start) { |
| 61 | + result.push_back(newInterval); |
| 62 | + // The newInterval overlaps with the preceding interval. |
| 63 | + } else if (newInterval.end > result.back().end) { |
| 64 | + result.back().end = newInterval.end; |
| 65 | + } |
| 66 | + |
| 67 | + for (; i<n; i++) { |
| 68 | + // The interval does not overlap with the preceding interval. |
| 69 | + if (intervals[i].start > result.back().end) { |
| 70 | + result.push_back(intervals[i]); |
| 71 | + // The interval overlap with the preceding interval. |
| 72 | + } else if (intervals[i].start <= result.back().end |
| 73 | + && intervals[i].end > result.back().end) { |
| 74 | + result.back().end = intervals[i].end; |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + return result; |
| 79 | + } |
| 80 | +}; |
0 commit comments