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]
.
bool CompInterval(const Interval& pl, const Interval& pr)
{
return pl.start < pr.start;
}
class Solution {
public:
vector<Interval> merge(vector<Interval>& intervals) {
if (intervals.empty() || intervals.size() == 1)
return intervals;
sort(intervals.begin(), intervals.end(), CompInterval);
int k = 0;
while (k + 1<intervals.size())
{
while (k + 1<intervals.size() && intervals[k].end < intervals[k + 1].start)
k++;
if (k + 1 == intervals.size())
return intervals;
int end = intervals[k].end >= intervals[k + 1].end
? intervals[k].end : intervals[k + 1].end;
int kk = k;
while (kk + 1 < intervals.size() && end >= intervals[kk + 1].start)
{
if (intervals[kk + 1].end > end)
end = intervals[kk + 1].end;
kk++;
}
intervals[k].end = end;
intervals.erase(intervals.begin() + k + 1, intervals.begin() + kk + 1);
k++;
}
return intervals;
}
};
accepted