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]
.
/**
* 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 compareInterval(const Interval &a, const Interval &b)
{
return a.start < b.start;
}
class Solution {
public:
vector<Interval> merge(vector<Interval> &intervals) {
vector<Interval> ivec;
if (intervals.size() == 0)
return ivec;
sort(intervals.begin(), intervals.end(), compareInterval);
Interval ival = intervals[0];
for (auto i = intervals.begin() + 1; i != intervals.end(); i++) {
if (ival.end >= (*i).start) {
if (ival.end < (*i).end)
ival.end = (*i).end;
continue;
}
else {
ivec.push_back(ival);
ival.start = (*i).start;
ival.end = (*i).end;
}
}
ivec.push_back(ival);
return ivec;
}
};