56 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].
Solution
/**
* 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) {
int n = intervals.size();
auto it = intervals.begin();
while ( it != intervals.end() ) {
int s = it->start, e = it->end;
if ( newInterval.end < s or e < newInterval.start ) {it++; continue;}
newInterval.start = min(s, newInterval.start);
newInterval.end = max(e, newInterval.end);
it = intervals.erase(it);
}
intervals.push_back(newInterval);
return intervals;
}
vector<Interval> merge(vector<Interval>& intervals) {
int n = intervals.size();
if ( n <= 1 ) return intervals;
vector<Interval> res(1, intervals[0]);
for ( int i = 1; i <= n-1; i++ ) res = insert(res, intervals[i]);
return res;
}
};
Notes
Insert intervals one by one.