Insert Interval
Given a setNon-overlappingIntervals, 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[1,5],[6,9]
.
Example 2:Given[1,2],[3,5],[6,7],[8,10],[12,16]
, Insert and merge[4,9]
In[1,2],[3,10],[12,16]
.
This is because the new interval[4,9]
Overlaps[3,5],[6,7],[8,10]
.
Idea: Because the intervals are in ascending order of START and there is no overlap. Therefore, the insertion interval and each element are considered in three situations. On the left side, on the right side (in these two cases, take the range directly) or cross (update the inserted range ). Use the variable out to determine whether a new interval has been placed.
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */class Solution {public: vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) { vector<Interval> vec; bool out = true; for(size_t i = 0; i < intervals.size(); ++i) { if(intervals[i].end < newInterval.start) { vec.push_back(intervals[i]); } else if(intervals[i].start > newInterval.end) { if(out) { vec.push_back(newInterval); out = false;} vec.push_back(intervals[i]); } else { newInterval.start = min(newInterval.start, intervals[i].start); newInterval.end = max(newInterval.end, intervals[i].end); } } if(out) vec.push_back(newInterval); return vec; }};
Merge intervals
Given a collection of intervals, merge all overlapping intervals.
For example, given[1,3],[2,6],[8,10],[15,18]
, Return[1,6],[8,10],[15,18]
.
Idea: sort by start first. Then, determine whether the current interval and the previous interval overlap. If there is no overlap, place it. If there is overlap, update the end of the previous interval and discard the current interval.
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */bool cmp(Interval a, Interval b) { return a.start < b.start;}class Solution {public: vector<Interval> merge(vector<Interval> &intervals) { sort(intervals.begin(), intervals.end(), cmp); vector<Interval> vec; for(size_t i = 0; i < intervals.size(); ++i) { if(vec.empty()) vec.push_back(intervals[i]); else if(intervals[i].start <= vec.back().end) vec.back().end = max(intervals[i].end, vec.back().end); else vec.push_back(intervals[i]); } return vec; }};
60. Insert interval & merge intervals